home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
MacWorld 1997 September
/
Macworld (1997-09).dmg
/
Shareware World
/
Utilities
/
Text Processing
/
Alpha
/
Help
/
Tcl Commands
< prev
next >
Wrap
Text File
|
1995-12-28
|
173KB
|
4,117 lines
Tcl Built-In Commands
_________________________________________________________________
NAME
Tcl - Summary of Tcl language syntax.
_________________________________________________________________
DESCRIPTION
The following rules define the syntax and semantics of the
Tcl language:
[1] A Tcl script is a string containing one or more com-
mands. Semi-colons and newlines are command separators
unless quoted as described below. Close brackets are
command terminators during command substitution (see
below) unless quoted.
[2] A command is evaluated in two steps. First, the Tcl
interpreter breaks the command into words and performs
substitutions as described below. These substitutions
are performed in the same way for all commands. The
first word is used to locate a command procedure to
carry out the command, then all of the words of the
command are passed to the command procedure. The com-
mand procedure is free to interpret each of its words
in any way it likes, such as an integer, variable name,
list, or Tcl script. Different commands interpret
their words differently.
[3] Words of a command are separated by white space (except
for newlines, which are command separators).
[4] If the first character of a word is double-quote
(``"'') then the word is terminated by the next
double-quote character. If semi-colons, close brack-
ets, or white space characters (including newlines)
appear between the quotes then they are treated as
ordinary characters and included in the word. Command
substitution, variable substitution, and backslash sub-
stitution are performed on the characters between the
quotes as described below. The double-quotes are not
retained as part of the word.
[5] If the first character of a word is an open brace
(``{'') then the word is terminated by the matching
close brace (``}''). Braces nest within the word: for
each additional open brace there must be an additional
close brace (however, if an open brace or close brace
within the word is quoted with a backslash then it is
not counted in locating the matching close brace). No
substitutions are performed on the characters between
the braces except for backslash-newline substitutions
described below, nor do semi-colons, newlines, close
brackets, or white space receive any special interpre-
tation. The word will consist of exactly the charac-
ters between the outer braces, not including the braces
themselves.
[6] If a word contains an open bracket (``['') then Tcl
performs command substitution. To do this it invokes
the Tcl interpreter recursively to process the charac-
ters following the open bracket as a Tcl script. The
script may contain any number of commands and must be
terminated by a close bracket (``]''). The result of
the script (i.e. the result of its last command) is
substituted into the word in place of the brackets and
all of the characters between them. There may be any
number of command substitutions in a single word. Com-
mand substitution is not performed on words enclosed in
braces.
[7] If a word contains a dollar-sign (``$'') then Tcl per-
forms variable substitution: the dollar-sign and the
following characters are replaced in the word by the
value of a variable. Variable substition may take any
of the following forms:
$name Name is the name of a scalar variable;
the name is terminated by any character
that isn't a letter, digit, or under-
score.
$name(index) Name gives the name of an array variable
and index gives the name of an element
within that array. Name must contain
only letters, digits, and underscores.
Command substitutions, variable substi-
tutions, and backslash substitutions are
performed on the characters of index.
${name} Name is the name of a scalar variable.
It may contain any characters whatsoever
except for close braces.
There may be any number of variable substitutions in a sin-
gle word. Variable substitution is not performed on words
enclosed in braces.
[8] If a backslash (``\'') appears within a word then
backslash substitution occurs. In all cases but those |
described below the backslash is dropped and the fol- |
lowing character is treated as an ordinary character |
and included in the word. This allows characters such
as double quotes, close brackets, and dollar signs to
be included in words without triggering special pro-
cessing. The following table lists the backslash
sequences that are handled specially, along with the
value that replaces each sequence.
\a ||
Audible alert (bell) (0x7).
\b Backspace (0x8).
\f Form feed (0xc).
\n Newline (0xa).
\r Carriage-return (0xd).
\t Tab (0x9).
\v Vertical tab (0xb).
\<newline>whiteSpace
A single space character replaces the backslash, |
newline, and all white space after the newline. |
This backslash sequence is unique in that it is |
replaced in a separate pre-pass before the com- |
mand is actually parsed. This means that it will |
be replaced even when it occurs between braces, |
and the resulting space will be treated as a word |
separator if it isn't in braces or quotes.
\\ Backslash (``\'').
\ooo The digits ooo (one, two, or three of them) give
the octal value of the character.
\xhh The hexadecimal digits hh give the hexadecimal |
value of the character. Any number of digits may |
be present.
Backslash substitution is not performed on words enclosed in
braces, except for backslash-newline as described above.
[9] If a hash character (``#'') appears at a point where
Tcl is expecting the first character of the first word
of a command, then the hash character and the charac-
ters that follow it, up through the next newline, are
treated as a comment and ignored. The comment charac-
ter only has significance when it appears at the begin-
ning of a command.
[10] Each character is processed exactly once by the Tcl
interpreter as part of creating the words of a command.
For example, if variable substition occurs then no
further substitions are performed on the value of the
variable; the value is inserted into the word verba-
tim. If command substitution occurs then the nested
command is processed entirely by the recursive call to
the Tcl interpreter; no substitutions are perfomed
before making the recursive call and no additional sub-
stitutions are performed on the result of the nested
script.
[11] Substitutions do not affect the word boundaries of a
command. For example, during variable substitution the
entire value of the variable becomes part of a single
word, even if the variable's value contains spaces.
Tcl Last change: 4
_________________________________________________________________
NAME
append - Append to variable
SYNOPSIS
append varName value ?value value ...?
_________________________________________________________________
DESCRIPTION
Append all of the value arguments to the current value of
variable varName. If varName doesn't exist, it is given a
value equal to the concatenation of all the value arguments.
This command provides an efficient way to build up long
variables incrementally. For example, ``append a $b'' is
much more efficient than ``set a $a$b'' if $a is long.
KEYWORDS
append, variable
_________________________________________________________________
NAME
array - Manipulate array variables
SYNOPSIS
array option arrayName ?arg arg ...?
_________________________________________________________________
DESCRIPTION
This command performs one of several operations on the vari-
able given by arrayName. ArrayName must be the name of an
existing array variable. The option argument determines
what action is carried out by the command. The legal
options (which may be abbreviated) are:
array anymore arrayName searchId
Returns 1 if there are any more elements left to be
processed in an array search, 0 if all elements have
already been returned. SearchId indicates which search
on arrayName to check, and must have been the return
value from a previous invocation of array startsearch.
This option is particularly useful if an array has an
element with an empty name, since the return value from
array nextelement won't indicate whether the search has
been completed.
array donesearch arrayName searchId
This command terminates an array search and destroys
all the state associated with that search. SearchId
indicates which search on arrayName to destroy, and
must have been the return value from a previous invoca-
tion of array startsearch. Returns an empty string.
array names arrayName
Returns a list containing the names of all of the ele-
ments in the array. If there are no elements in the
array then an empty string is returned.
array nextelement arrayName searchId
Returns the name of the next element in arrayName, or
an empty string if all elements of arrayName have
already been returned in this search. The searchId
argument identifies the search, and must have been the
return value of an array startsearch command. Warning:
if elements are added to or deleted from the array,
then all searches are automatically terminated just as
if array donesearch had been invoked; this will cause
array nextelement operations to fail for those
searches.
array size arrayName
Returns a decimal string giving the number of elements
in the array.
array startsearch arrayName
This command initializes an element-by-element search
through the array given by arrayName, such that invoca-
tions of the array nextelement command will return the
names of the individual elements in the array. When
the search has been completed, the array donesearch
command should be invoked. The return value is a
search identifier that must be used in array nextele-
ment and array donesearch commands; it allows multiple
searches to be underway simultaneously for the same
array.
KEYWORDS
array, element names, search
_________________________________________________________________
NAME
break - Abort looping command
SYNOPSIS
break
_________________________________________________________________
DESCRIPTION
This command may be invoked only inside the body of a loop-
ing command such as for or foreach or while. It returns a
TCL_BREAK code to signal the innermost containing loop com-
mand to return immediately.
KEYWORDS
abort, break, loop
_________________________________________________________________
NAME
case - Evaluate one of several scripts, depending on a given
value
SYNOPSIS
case string ?in? patList body ?patList body ...?
case string ?in? {patList body ?patList body ...?}
_________________________________________________________________
DESCRIPTION
Note: the case command is obsolete and is supported only for
backward compatibility. At some point in the future it may
be removed entirely. You should use the switch command
instead.
The case command matches string against each of the patList
arguments in order. Each patList argument is a list of one
or more patterns. If any of these patterns matches string
then case evaluates the following body argument by passing
it recursively to the Tcl interpreter and returns the result
of that evaluation. Each patList argument consists of a
single pattern or list of patterns. Each pattern may con-
tain any of the wild-cards described under string match. If
a patList argument is default, the corresponding body will
be evaluated if no patList matches string. If no patList
argument matches string and no default is given, then the
case command returns an empty string.
Two syntaxes are provided for the patList and body argu-
ments. The first uses a separate argument for each of the
patterns and commands; this form is convenient if substitu-
tions are desired on some of the patterns or commands. The
second form places all of the patterns and commands together
into a single argument; the argument must have proper list
structure, with the elements of the list being the patterns
and commands. The second form makes it easy to construct
multi-line case commands, since the braces around the whole
list make it unnecessary to include a backslash at the end
of each line. Since the patList arguments are in braces in
the second form, no command or variable substitutions are
performed on them; this makes the behavior of the second
form different than the first form in some cases.
KEYWORDS
case, match, regular expression
_________________________________________________________________
NAME
catch - Evaluate script and trap exceptional returns
SYNOPSIS
catch script ?varName?
_________________________________________________________________
DESCRIPTION
The catch command may be used to prevent errors from abort-
ing command interpretation. Catch calls the Tcl interpreter
recursively to execute script, and always returns a TCL_OK
code, regardless of any errors that might occur while exe-
cuting script. The return value from catch is a decimal
string giving the code returned by the Tcl interpreter after
executing script. This will be 0 (TCL_OK) if there were no
errors in script; otherwise it will have a non-zero value
corresponding to one of the exceptional return codes (see
tcl.h for the definitions of code values). If the varName
argument is given, then it gives the name of a variable;
catch will set the variable to the string returned from
script (either a result or an error message).
KEYWORDS
catch, error
_________________________________________________________________
NAME
cd - Change working directory
SYNOPSIS
cd ?dirName?
_________________________________________________________________
DESCRIPTION
Change the current working directory to dirName, or to the
home directory (as specified in the HOME environment vari-
able) if dirName is not given. If dirName starts with a
tilde, then tilde-expansion is done as described for
Tcl_TildeSubst. Returns an empty string.
KEYWORDS
working directory
_________________________________________________________________
NAME
close - Close an open file
SYNOPSIS
close fileId
_________________________________________________________________
DESCRIPTION
Closes the file given by fileId. FileId must be the return
value from a previous invocation of the open command; after
this command, it should not be used anymore. If fileId
refers to a command pipeline instead of a file, then close
waits for the children to complete. The normal result of
this command is an empty string, but errors are returned if
there are problems in closing the file or waiting for chil-
dren to complete.
KEYWORDS
close, file
_________________________________________________________________
NAME
concat - Join lists together
SYNOPSIS
concat ?arg arg ...? |
_________________________________________________________________
DESCRIPTION
This command treats each argument as a list and concatenates
them into a single list. It also eliminates leading and
trailing spaces in the arg's and adds a single separator
space between arg's. It permits any number of arguments.
For example, the command
concat a b {c d e} {f {g h}}
will return
a b c d e f {g h}
as its result.
If no args are supplied, the result is an empty string. |
KEYWORDS
concatenate, join, lists
_________________________________________________________________
NAME
continue - Skip to the next iteration of a loop
SYNOPSIS
continue
_________________________________________________________________
DESCRIPTION
This command may be invoked only inside the body of a loop-
ing command such as for or foreach or while. It returns a
TCL_CONTINUE code to signal the innermost containing loop
command to skip the remainder of the loop's body but con-
tinue with the next iteration of the loop.
KEYWORDS
continue, iteration, loop
_________________________________________________________________
NAME
eof - Check for end-of-file condition on open file
SYNOPSIS
eof fileId
_________________________________________________________________
DESCRIPTION
Returns 1 if an end-of-file condition has occurred on
fileId, 0 otherwise. FileId must have been the return value
from a previous call to open, or it may be stdin, stdout, or
stderr to refer to one of the standard I/O channels.
KEYWORDS
end, file
_________________________________________________________________
NAME
error - Generate an error
SYNOPSIS
error message ?info? ?code?
_________________________________________________________________
DESCRIPTION
Returns a TCL_ERROR code, which causes command interpreta-
tion to be unwound. Message is a string that is returned to
the application to indicate what went wrong.
If the info argument is provided and is non-empty, it is
used to initialize the global variable errorInfo. errorInfo
is used to accumulate a stack trace of what was in progress
when an error occurred; as nested commands unwind, the Tcl
interpreter adds information to errorInfo. If the info
argument is present, it is used to initialize errorInfo and
the first increment of unwind information will not be added
by the Tcl interpreter. In other words, the command con-
taining the error command will not appear in errorInfo; in
its place will be info. This feature is most useful in con-
junction with the catch command: if a caught error cannot be
handled successfully, info can be used to return a stack
trace reflecting the original point of occurrence of the
error:
catch {...} errMsg
set savedInfo $errorInfo
...
error $errMsg $savedInfo
If the code argument is present, then its value is stored in
the errorCode global variable. This variable is intended to
hold a machine-readable description of the error in cases
where such information is available; see the section BUILT-
IN VARIABLES below for information on the proper format for
the variable. If the code argument is not present, then
errorCode is automatically reset to ``NONE'' by the Tcl
interpreter as part of processing the error generated by the
command.
KEYWORDS
error, errorCode, errorInfo
_________________________________________________________________
NAME
eval - Evaluate a Tcl script
SYNOPSIS
eval arg ?arg ...?
_________________________________________________________________
DESCRIPTION
Eval takes one or more arguments, which together comprise a
Tcl script containing one or more commands. Eval concaten-
ates all its arguments in the same fashion as the concat
command, passes the concatenated string to the Tcl inter-
preter recursively, and returns the result of that evalua-
tion (or any error generated by it).
KEYWORDS
concatenate, evaluate, script
_________________________________________________________________
NAME
exec - Invoke subprocess(es)
SYNOPSIS
exec ?switches? arg ?arg ...?
_________________________________________________________________
DESCRIPTION
This command treats its arguments as the specification of
one or more subprocesses to execute. The arguments take the
form of a standard shell pipeline where each arg becomes one
word of a command, and each distinct command becomes a sub-
process.
If the initial arguments to exec start with - then they are |
treated as command-line switches and are not part of the |
pipeline specification. The following switches are |
currently supported: |
-keepnew- |
line ||
Retains a trailing newline in the pipeline's |
output. Normally a trailing newline will be |
deleted. |
-- ||
Marks the end of switches. The argument fol- |
lowing this one will be treated as the first |
arg even if it starts with a -.
If an arg (or pair of arg's) has one of the forms described
below then it is used by exec to control the flow of input
and output among the subprocess(es). Such arguments will
not be passed to the subprocess(es). In forms such as ``< |
fileName'' fileName may either be in a separate argument |
from ``<'' or in the same argument with no intervening space |
(i.e. ``<fileName'').
| Separates distinct commands in the pipeline.
The standard output of the preceding command
will be piped into the standard input of the
next command.
|& Separates distinct commands in the pipeline.
Both standard output and standard error of
the preceding command will be piped into the
standard input of the next command. This
form of redirection overrides forms such as
2> and >&.
< fileName The file named by fileName is opened and used
as the standard input for the first command
in the pipeline.
<@ fileId FileId must be the identifier for an open |
file, such as the return value from a previ- |
ous call to open. It is used as the standard |
input for the first command in the pipeline. |
FileId must have been opened for reading.
<< value Value is passed to the first command as its
standard input.
> fileName Standard output from the last command is
redirected to the file named fileName,
overwriting its previous contents.
2> fileName Standard error from all commands in the pipe- |
line is redirected to the file named |
fileName, overwriting its previous contents. |
>& fileName ||
Both standard output from the last command |
and standard error from all commands are |
redirected to the file named fileName, |
overwriting its previous contents.
>> fileName Standard output from the last command is
redirected to the file named fileName,
appending to it rather than overwriting it.
2>> fileName Standard error from all commands in the pipe- |
line is redirected to the file named |
fileName, appending to it rather than |
overwriting it. |
>>& fileName ||
Both standard output from the last command |
and standard error from all commands are |
redirected to the file named fileName, |
appending to it rather than overwriting it. |
>@ fileId ||
FileId must be the identifier for an open |
file, such as the return value from a previ- |
ous call to open. Standard output from the |
last command is redirected to fileId's file, |
which must have been opened for writing. |
2>@ fileId ||
FileId must be the identifier for an open |
file, such as the return value from a |
previous call to open. Standard error from |
all commands in the pipeline is redirected to |
fileId's file. The file must have been |
opened for writing. |
>&@ fileId ||
FileId must be the identifier for an open |
file, such as the return value from a previ- |
ous call to open. Both standard output from |
the last command and standard error from all |
commands are redirected to fileId's file. |
The file must have been opened for writing.
If standard output has not been redirected then the exec
command returns the standard output from the last command in
the pipeline. If any of the commands in the pipeline exit
abnormally or are killed or suspended, then exec will return
an error and the error message will include the pipeline's
output followed by error messages describing the abnormal
terminations; the errorCode variable will contain additional
information about the last abnormal termination encountered.
If any of the commands writes to its standard error file and
that standard error isn't redirected, then exec will return
an error; the error message will include the pipeline's
standard output, followed by messages about abnormal termi-
nations (if any), followed by the standard error output.
If the last character of the result or error message is a
newline then that character is normally deleted from the
result or error message. This is consistent with other Tcl
return values, which don't normally end with newlines. How- |
ever, if -keepnewline is specified then the trailing newline |
is retained.
If standard input isn't redirected with ``<'' or ``<<'' or
``<@'' then the standard input for the first command in the
pipeline is taken from the application's current standard
input.
If the last arg is ``&'' then the pipeline will be executed
in background. In this case the exec command will return a |
list whose elements are the process identifiers for all of |
the subprocesses in the pipeline. The standard output from
the last command in the pipeline will go to the
application's standard output if it hasn't been redirected,
and error output from all of the commands in the pipeline
will go to the application's standard error file unless
redirected.
The first word in each command is taken as the command name;
tilde-substitution is performed on it, and if the result
contains no slashes then the directories in the PATH
environment variable are searched for an executable by the
given name. If the name contains a slash then it must refer
to an executable reachable from the current directory. No
``glob'' expansion or other shell-like substitutions are
performed on the arguments to commands.
KEYWORDS
execute, pipeline, redirection, subprocess
_________________________________________________________________
NAME
exit - End the application
SYNOPSIS
exit ?returnCode?
_________________________________________________________________
DESCRIPTION
Terminate the process, returning returnCode to the system as
the exit status. If returnCode isn't specified then it
defaults to 0.
KEYWORDS
exit, process
_________________________________________________________________
NAME
expr - Evalue an expression
SYNOPSIS
expr arg ?arg arg ...?
_________________________________________________________________
DESCRIPTION
Concatenates arg's (adding separator spaces between them), |
evaluates the result as a Tcl expression, and returns the |
value. The operators permitted in Tcl expressions are a
subset of the operators permitted in C expressions, and they
have the same meaning and precedence as the corresponding C
operators. Expressions almost always yield numeric results
(integer or floating-point values). For example, the
expression
expr 8.2 + 6
evaluates to 14.2. Tcl expressions differ from C expres-
sions in the way that operands are specified. Also, Tcl
expressions support non-numeric operands and string com-
parisons.
OPERANDS
A Tcl expression consists of a combination of operands,
operators, and parentheses. White space may be used between
the operands and operators and parentheses; it is ignored by
the expression processor. Where possible, operands are
interpreted as integer values. Integer values may be speci-
fied in decimal (the normal case), in octal (if the first
character of the operand is 0), or in hexadecimal (if the
first two characters of the operand are 0x). If an operand
does not have one of the integer formats given above, then
it is treated as a floating-point number if that is possi-
ble. Floating-point numbers may be specified in any of the
ways accepted by an ANSI-compliant C compiler (except that
the ``f'', ``F'', ``l'', and ``L'' suffixes will not be per-
mitted in most installations). For example, all of the fol-
lowing are valid floating-point numbers: 2.1, 3., 6e4,
7.91e+16. If no numeric interpretation is possible, then an
operand is left as a string (and only a limited set of
operators may be applied to it).
Operands may be specified in any of the following ways:
[1] As an numeric value, either integer or floating-point.
[2] As a Tcl variable, using standard $ notation. The
variable's value will be used as the operand.
[3] As a string enclosed in double-quotes. The expression
parser will perform backslash, variable, and command
substitutions on the information between the quotes,
and use the resulting value as the operand
[4] As a string enclosed in braces. The characters between
the open brace and matching close brace will be used as
the operand without any substitutions.
[5] As a Tcl command enclosed in brackets. The command
will be executed and its result will be used as the
operand.
[6] As a mathematical function whose arguments have any of |
the above forms for operands, such as ``sin($x)''. See |
below for a list of defined functions.
Where substitutions occur above (e.g. inside quoted
strings), they are performed by the expression processor.
However, an additional layer of substitution may already
have been performed by the command parser before the expres-
sion processor was called. As discussed below, it is usu-
ally best to enclose expressions in braces to prevent the
command parser from performing substitutions on the con-
tents.
For some examples of simple expressions, suppose the vari-
able a has the value 3 and the variable b has the value 6.
Then the command on the left side of each of the lines below
will produce the value on the right side of the line:
expr 3.1 + $a 6.1
expr 2 + "$a.$b" 5.6
expr 4*[llength "6 2"] 8
expr {{word one} < "word $a"}0
OPERATORS
The valid operators are listed below, grouped in decreasing
order of precedence:
- ~ ! Unary minus, bit-wise NOT, logical NOT.
None of these operands may be applied to
string operands, and bit-wise NOT may be
applied only to integers.
* / % Multiply, divide, remainder. None of
these operands may be applied to string
operands, and remainder may be applied
only to integers. The remainder will |
always have the same sign as the divisor |
and an absolute value smaller than the |
divisor.
+ - Add and subtract. Valid for any numeric
operands.
<< >> Left and right shift. Valid for integer
operands only.
< > <= >= Boolean less, greater, less than or
equal, and greater than or equal. Each
operator produces 1 if the condition is
true, 0 otherwise. These operators may
be applied to strings as well as numeric
operands, in which case string com-
parison is used.
== != Boolean equal and not equal. Each
operator produces a zero/one result.
Valid for all operand types.
& Bit-wise AND. Valid for integer
operands only.
^ Bit-wise exclusive OR. Valid for
integer operands only.
| Bit-wise OR. Valid for integer operands
only.
&& Logical AND. Produces a 1 result if
both operands are non-zero, 0 otherwise.
Valid for numeric operands only
(integers or floating-point).
|| Logical OR. Produces a 0 result if both
operands are zero, 1 otherwise. Valid
for numeric operands only (integers or
floating-point).
x?y:z If-then-else, as in C. If x evaluates
to non-zero, then the result is the
value of y. Otherwise the result is the
value of z. The x operand must have a
numeric value.
See the C manual for more details on the results produced by
each operator. All of the binary operators group left-to-
right within the same precedence level. For example, the
command
expr 4*2 < 7
returns 0.
The &&, ||, and ?: operators have ``lazy evaluation'', just
as in C, which means that operands are not evaluated if they
are not needed to determine the outcome. For example, in
the command
expr {$v ? [a] : [b]}
only one of [a] or [b] will actually be evaluated, depending
on the value of $v. Note, however, that this is only true
if the entire expression is enclosed in braces; otherwise
the Tcl parser will evaluate both [a] and [b] before invok-
ing the expr command.
MATH FUNCTIONS
Tcl supports the following mathematical functions in expres- |
sions: |
acos cos hypot sinh |
asin cosh log sqrt |
atan exp log10 tan |
atan2 floor pow tanh |
ceil fmod sin |
Each of these functions invokes the math library function of |
the same name; see the manual entries for the library func- |
tions for details on what they do. Tcl also implements the |
following functions for conversion between integers and |
floating-point numbers: |
abs(arg) ||
Returns the absolute value of arg. Arg may be either |
integer or floating-point, and the result is returned |
in the same form. |
double(arg) ||
If arg is a floating value, returns arg, otherwise con- |
verts arg to floating and returns the converted value. |
int(arg) ||
If arg is an integer value, returns arg, otherwise con- |
verts arg to integer by truncation and returns the con- |
verted value. |
round(arg) ||
If arg is an integer value, returns arg, otherwise con- |
verts arg to integer by rounding and returns the con- |
verted value. |
In addition to these predifined functions, applications may |
define additional functions using Tcl_CreateMathFunc().
TYPES, OVERFLOW, AND PRECISION
All internal computations involving integers are done with
the C type long, and all internal computations involving
floating-point are done with the C type double. When con-
verting a string to floating-point, exponent overflow is
detected and results in a Tcl error. For conversion to
integer from string, detection of overflow depends on the
behavior of some routines in the local C library, so it
should be regarded as unreliable. In any case, integer
overflow and underflow are generally not detected reliably
for intermediate results. Floating-point overflow and
underflow are detected to the degree supported by the
hardware, which is generally pretty reliable.
Conversion among internal representations for integer,
floating-point, and string operands is done automatically as
needed. For arithmetic computations, integers are used
until some floating-point number is introduced, after which
floating-point is used. For example,
expr 5 / 4
returns 1, while
expr 5 / 4.0
expr 5 / ( [string length "abcd"] + 0.0 )
both return 1.25. Floating-point values are always returned |
with a ``.'' or an ``e'' so that they will not look like |
integer values. For example, |
expr 20.0/5.0 |
returns ``4.0'', not ``4''. The global variable |
tcl_precision determines the the number of significant |
digits that are retained when floating values are converted |
to strings (except that trailing zeroes are omitted). If |
tcl_precision is unset then 6 digits of precision are used. |
To retain all of the significant bits of an IEEE floating- |
point number set tcl_precision to 17; if a value is con- |
verted to string with 17 digits of precision and then con- |
verted back to binary for some later calculation, the |
resulting binary value is guaranteed to be identical to the |
original one.
STRING OPERATIONS
String values may be used as operands of the comparison
operators, although the expression evaluator tries to do
comparisons as integer or floating-point when it can. If
one of the operands of a comparison is a string and the
other has a numeric value, the numeric operand is converted
back to a string using the C sprintf format specifier %d for
integers and %g for floating-point values. For example, the
commands
expr {"0x03" > "2"}
expr {"0y" < "0x12"}
both return 1. The first comparison is done using integer
comparison, and the second is done using string comparison
after the second operand is converted to the string ``18''.
KEYWORDS
arithmetic, boolean, compare, expression
_________________________________________________________________
NAME
file - Manipulate file names and attributes
SYNOPSIS
file option name ?arg arg ...?
_________________________________________________________________
DESCRIPTION
This command provides several operations on a file's name or
attributes. Name is the name of a file; if it starts with a
tilde, then tilde substitution is done before executing the
command (see the manual entry for Tcl_TildeSubst for
details). Option indicates what to do with the file name.
Any unique abbreviation for option is acceptable. The valid
options are:
file atime name
Returns a decimal string giving the time at which file
name was last accessed. The time is measured in the
standard POSIX fashion as seconds from a fixed starting
time (often January 1, 1970). If the file doesn't
exist or its access time cannot be queried then an
error is generated.
file dirname name
Returns all of the characters in name up to but not
including the last slash character. If there are no
slashes in name then returns ``.''. If the last slash
in name is its first character, then return ``/''.
file executable name
Returns 1 if file name is executable by the current
user, 0 otherwise.
file exists name
Returns 1 if file name exists and the current user has
search privileges for the directories leading to it, 0
otherwise.
file extension name
Returns all of the characters in name after and includ-
ing the last dot in name. If there is no dot in name
then returns the empty string.
file isdirectory name
Returns 1 if file name is a directory, 0 otherwise.
file isfile name
Returns 1 if file name is a regular file, 0 otherwise.
file lstat name varName
Same as stat option (see below) except uses the lstat
kernel call instead of stat. This means that if name
refers to a symbolic link the information returned in
varName is for the link rather than the file it refers
to. On systems that don't support symbolic links this
option behaves exactly the same as the stat option.
file mtime name
Returns a decimal string giving the time at which file
name was last modified. The time is measured in the
standard POSIX fashion as seconds from a fixed starting
time (often January 1, 1970). If the file doesn't
exist or its modified time cannot be queried then an
error is generated.
file owned name
Returns 1 if file name is owned by the current user, 0
otherwise.
file readable name
Returns 1 if file name is readable by the current user,
0 otherwise.
file readlink name
Returns the value of the symbolic link given by name
(i.e. the name of the file it points to). If name
isn't a symbolic link or its value cannot be read, then
an error is returned. On systems that don't support
symbolic links this option is undefined.
file rootname name
Returns all of the characters in name up to but not
including the last ``.'' character in the name. If
name doesn't contain a dot, then returns name.
file size name
Returns a decimal string giving the size of file name
in bytes. If the file doesn't exist or its size cannot
be queried then an error is generated.
file stat name varName
Invokes the stat kernel call on name, and uses the
variable given by varName to hold information returned
from the kernel call. VarName is treated as an array
variable, and the following elements of that variable
are set: atime, ctime, dev, gid, ino, mode, mtime,
nlink, size, type, uid. Each element except type is a
decimal string with the value of the corresponding
field from the stat return structure; see the manual
entry for stat for details on the meanings of the
values. The type element gives the type of the file in
the same form returned by the command file type. This
command returns an empty string.
file tail name
Returns all of the characters in name after the last
slash. If name contains no slashes then returns name.
file type name
Returns a string giving the type of file name, which
will be one of file, directory, characterSpecial,
blockSpecial, fifo, link, or socket.
file writable name
Returns 1 if file name is writable by the current user,
0 otherwise.
KEYWORDS
attributes, directory, file, name, stat
_________________________________________________________________
NAME
flush - Flush buffered output for a file
SYNOPSIS
flush fileId
_________________________________________________________________
DESCRIPTION
Flushes any output that has been buffered for fileId.
FileId must have been the return value from a previous call
to open, or it may be stdout or stderr to access one of the
standard I/O streams; it must refer to a file that was
opened for writing. The command returns an empty string.
KEYWORDS
buffer, file, flush, output
_________________________________________________________________
NAME
for - ``For'' loop
SYNOPSIS
for start test next body
_________________________________________________________________
DESCRIPTION
For is a looping command, similar in structure to the C for
statement. The start, next, and body arguments must be Tcl
command strings, and test is an expression string. The for
command first invokes the Tcl interpreter to execute start.
Then it repeatedly evaluates test as an expression; if the
result is non-zero it invokes the Tcl interpreter on body,
then invokes the Tcl interpreter on next, then repeats the
loop. The command terminates when test evaluates to 0. If
a continue command is invoked within body then any remaining
commands in the current execution of body are skipped; pro-
cessing continues by invoking the Tcl interpreter on next,
then evaluating test, and so on. If a break command is
invoked within body or next, then the for command will
return immediately. The operation of break and continue are
similar to the corresponding statements in C. For returns
an empty string.
KEYWORDS
for, iteration, looping
_________________________________________________________________
NAME
foreach - Iterate over all elements in a list
SYNOPSIS
foreach varname list body
_________________________________________________________________
DESCRIPTION
In this command varname is the name of a variable, list is a
list of values to assign to varname, and body is a Tcl
script. For each element of list (in order from left to
right), foreach assigns the contents of the field to varname
as if the lindex command had been used to extract the field,
then calls the Tcl interpreter to execute body. The break
and continue statements may be invoked inside body, with the
same effect as in the for command. Foreach returns an empty
string.
KEYWORDS
foreach, iteration, list, looping
_________________________________________________________________
NAME
format - Format a string in the style of sprintf
SYNOPSIS
format formatString ?arg arg ...?
_________________________________________________________________
INTRODUCTION
This command generates a formatted string in the same way as
the ANSI C sprintf procedure (it uses sprintf in its imple-
mentation). FormatString indicates how to format the
result, using % conversion specifiers as in sprintf, and the
additional arguments, if any, provide values to be substi-
tuted into the result. The return value from format is the
formatted string.
DETAILS ON FORMATTING
The command operates by scanning formatString from left to
right. Each character from the format string is appended to
the result string unless it is a percent sign. If the char-
acter is a % then it is not copied to the result string.
Instead, the characters following the % character are
treated as a conversion specifier. The conversion specifier
controls the conversion of the next successive arg to a par-
ticular format and the result is appended to the result
string in place of the conversion specifier. If there are
multiple conversion specifiers in the format string, then
each one controls the conversion of one additional arg. The
format command must be given enough args to meet the needs
of all of the conversion specifiers in formatString.
Each conversion specifier may contain up to six different
parts: an XPG3 position specifier, a set of flags, a minimum |
field width, a precision, a length modifier, and a conver-
sion character. Any of these fields may be omitted except
for the conversion character. The fields that are present
must appear in the order given above. The paragraphs below
discuss each of these fields in turn.
If the % is followed by a decimal number and a $, as in |
``%2$d'', then the value to convert is not taken from the |
next sequential argument. Instead, it is taken from the |
argument indicated by the number, where 1 corresponds to the |
first arg. If the conversion specifier requires multiple |
arguments because of * characters in the specifier then suc- |
cessive arguments are used, starting with the argument given |
by the number. This follows the XPG3 conventions for posi- |
tional specifiers. If there are any positional specifiers |
in formatString then all of the specifiers must be posi- |
tional.
The second portion of a conversion specifier may contain any
of the following flag characters, in any order:
- Specifies that the converted argument should be
left-justified in its field (numbers are normally
right-justified with leading spaces if needed).
+ Specifies that a number should always be printed
with a sign, even if positive.
space Specifies that a space should be added to the
beginning of the number if the first character
isn't a sign.
0 Specifies that the number should be padded on the
left with zeroes instead of spaces.
# Requests an alternate output form. For o and O
conversions it guarantees that the first digit is
always 0. For x or X conversions, 0x or 0X
(respectively) will be added to the beginning of
the result unless it is zero. For all floating-
point conversions (e, E, f, g, and G) it guaran-
tees that the result always has a decimal point.
For g and G conversions it specifies that trailing
zeroes should not be removed.
The third portion of a conversion specifier is a number giv-
ing a minimum field width for this conversion. It is typi-
cally used to make columns line up in tabular printouts. If
the converted argument contains fewer characters than the
minimum field width then it will be padded so that it is as
wide as the minimum field width. Padding normally occurs by
adding extra spaces on the left of the converted argument,
but the 0 and - flags may be used to specify padding with
zeroes on the left or with spaces on the right, respec-
tively. If the minimum field width is specified as * rather
than a number, then the next argument to the format command
determines the minimum field width; it must be a numeric
string.
The fourth portion of a conversion specifier is a precision,
which consists of a period followed by a number. The number
is used in different ways for different conversions. For e,
E, and f conversions it specifies the number of digits to
appear to the right of the decimal point. For g and G
conversions it specifies the total number of digits to
appear, including those on both sides of the decimal point
(however, trailing zeroes after the decimal point will still
be omitted unless the # flag has been specified). For
integer conversions, it specifies a mimimum number of digits
to print (leading zeroes will be added if necessary). For s
conversions it specifies the maximum number of characters to
be printed; if the string is longer than this then the
trailing characters will be dropped. If the precision is
specified with * rather than a number then the next argument
to the format command determines the precision; it must be a
numeric string.
The fourth part of a conversion specifier is a length modif-
ier, which must be h or l. If it is h it specifies that the
numeric value should be truncated to a 16-bit value before
converting. This option is rarely useful. The l modifier
is ignored.
The last thing in a conversion specifier is an alphabetic
character that determines what kind of conversion to per-
form. The following conversion characters are currently
supported:
d Convert integer to signed decimal string.
u Convert integer to unsigned decimal string.
i Convert integer to signed decimal string; the
integer may either be in decimal, in octal (with a
leading 0) or in hexadecimal (with a leading 0x).
o Convert integer to unsigned octal string.
x or X Convert integer to unsigned hexadecimal string,
using digits ``0123456789abcdef'' for x and
``0123456789ABCDEF'' for X).
c Convert integer to the 8-bit character it
represents.
s No conversion; just insert string.
f Convert floating-point number to signed decimal
string of the form xx.yyy, where the number of y's
is determined by the precision (default: 6). If
the precision is 0 then no decimal point is out-
put.
e or e Convert floating-point number to scientific nota-
tion in the form x.yyye+__zz, where the number of
y's is determined by the precision (default: 6).
If the precision is 0 then no decimal point is
output. If the E form is used then E is printed
instead of e.
g or G If the exponent is less than -4 or greater than or
equal to the precision, then convert floating-
point number as for %e or %E. Otherwise convert
as for %f. Trailing zeroes and a trailing decimal
point are omitted.
% No conversion: just insert %.
For the numerical conversions the argument being converted
must be an integer or floating-point string; format converts
the argument to binary and then converts it back to a string
according to the conversion specifier.
DIFFERENCES FROM ANSI SPRINTF
The behavior of the format command is the same as the ANSI C |
sprintf procedure except for the following differences: |
[1] ||
%p and %n specifiers are not currently supported.
[2] For %c conversions the argument must be a decimal
string, which will then be converted to the correspond-
ing character value.
[3] The l modifier is ignored; integer values are always |
converted as if there were no modifier present and real |
values are always converted as if the l modifier were |
present (i.e. type double is used for the internal |
representation). If the h modifier is specified then |
integer values are truncated to short before conver- |
sion.
KEYWORDS
conversion specifier, format, sprintf, string, substitution
_________________________________________________________________
NAME
gets - Read a line from a file
SYNOPSIS
gets fileId ?varName?
_________________________________________________________________
DESCRIPTION
This command reads the next line from the file given by
fileId and discards the terminating newline character. If
varName is specified then the line is placed in the variable
by that name and the return value is a count of the number
of characters read (not including the newline). If the end
of the file is reached before reading any characters then -1
is returned and varName is set to an empty string. If var-
Name is not specified then the return value will be the line
(minus the newline character) or an empty string if the end
of the file is reached before reading any characters. An
empty string will also be returned if a line contains no
characters except the newline, so eof may have to be used to
determine what really happened. If the last character in
the file is not a newline character then gets behaves as if
there were an additional newline character at the end of the
file. FileId must be stdin or the return value from a pre-
vious call to open; it must refer to a file that was opened
for reading. Any existing end-of-file or error condition on |
the file is cleared at the beginning of the gets command.
KEYWORDS
file, line, read
_________________________________________________________________
NAME
glob - Return names of files that match patterns
SYNOPSIS
glob ?switches? pattern ?pattern ...?
_________________________________________________________________
DESCRIPTION
This command performs file name ``globbing'' in a fashion
similar to the csh shell. It returns a list of the files
whose names match any of the pattern arguments.
If the initial arguments to glob start with - then they are |
treated as switches. The following switches are currently |
supported: |
-nocom- |
plain ||
Allows an empty list to be returned without |
error; without this switch an error is |
returned if the result list would be empty. |
-- ||
Marks the end of switches. The argument fol- |
lowing this one will be treated as a pattern |
even if it starts with a -.
The pattern arguments may contain any of the following spe-
cial characters:
? Matches any single character.
* Matches any sequence of zero or more characters.
[chars] Matches any single character in chars. If chars
contains a sequence of the form a-b then any char-
acter between a and b (inclusive) will match.
\x Matches the character x.
{a,b,...} Matches any of the strings a, b, etc.
As with csh, a ``.'' at the beginning of a file's name or
just after a ``/'' must be matched explicitly or with a {}
construct. In addition, all ``/'' characters must be
matched explicitly.
If the first character in a pattern is ``~'' then it refers
to the home directory for the user whose name follows the
``~''. If the ``~'' is followed immediately by ``/'' then
the value of the HOME environment variable is used.
The glob command differs from csh globbing in two ways.
First, it does not sort its result list (use the lsort com-
mand if you want the list sorted). Second, glob only |
returns the names of files that actually exist; in csh no |
check for existence is made unless a pattern contains a ?, |
*, or [] construct.
KEYWORDS
exist, file, glob, pattern
_________________________________________________________________
NAME
global - Access global variables
SYNOPSIS
global varname ?varname ...?
_________________________________________________________________
DESCRIPTION
This command is ignored unless a Tcl procedure is being
interpreted. If so then it declares the given varname's to
be global variables rather than local ones. For the dura-
tion of the current procedure (and only while executing in
the current procedure), any reference to any of the varnames
will refer to the global variable by the same name.
KEYWORDS
global, procedure, variable
_________________________________________________________________
NAME
history - Manipulate the history list
SYNOPSIS
history ?option? ?arg arg ...?
_________________________________________________________________
DESCRIPTION
The history command performs one of several operations
related to recently-executed commands recorded in a history
list. Each of these recorded commands is referred to as an
``event''. When specifying an event to the history command,
the following forms may be used:
[1] A number: if positive, it refers to the event with
that number (all events are numbered starting at 1).
If the number is negative, it selects an event relative
to the current event (-1 refers to the previous event,
-2 to the one before that, and so on).
[2] A string: selects the most recent event that matches
the string. An event is considered to match the string
either if the string is the same as the first charac-
ters of the event, or if the string matches the event
in the sense of the string match command.
The history command can take any of the following forms:
history
Same as history info, described below.
history add command ?exec?
Adds the command argument to the history list as a new
event. If exec is specified (or abbreviated) then the
command is also executed and its result is returned.
If exec isn't specified then an empty string is
returned as result.
history change newValue ?event?
Replaces the value recorded for an event with newValue.
Event specifies the event to replace, and defaults to
the current event (not event -1). This command is
intended for use in commands that implement new forms
of history substitution and wish to replace the current
event (which invokes the substitution) with the command
created through substitution. The return value is an
empty string.
history event ?event?
Returns the value of the event given by event. Event
defaults to -1. This command causes history revision
to occur: see below for details.
history info ?count?
Returns a formatted string (intended for humans to
read) giving the event number and contents for each of
the events in the history list except the current
event. If count is specified then only the most recent
count events are returned.
history keep count
This command may be used to change the size of the his-
tory list to count events. Initially, 20 events are
retained in the history list. This command returns an
empty string.
history nextid
Returns the number of the next event to be recorded in
the history list. It is useful for things like print-
ing the event number in command-line prompts.
history redo ?event?
Re-executes the command indicated by event and return
its result. Event defaults to -1. This command
results in history revision: see below for details.
history substitute old new ?event?
Retrieves the command given by event (-1 by default),
replace any occurrences of old by new in the command
(only simple character equality is supported; no wild
cards), execute the resulting command, and return the
result of that execution. This command results in his-
tory revision: see below for details.
history words selector ?event?
Retrieves from the command given by event (-1 by
default) the words given by selector, and return those
words in a string separated by spaces. The selector
argument has three forms. If it is a single number
then it selects the word given by that number (0 for
the command name, 1 for its first argument, and so on).
If it consists of two numbers separated by a dash, then
it selects all the arguments between those two. Other-
wise selector is treated as a pattern; all words match-
ing that pattern (in the sense of string match) are
returned. In the numeric forms $ may be used to select
the last word of a command. For example, suppose the
most recent command in the history list is
format {%s is %d years old} Alice [expr $ageInMonths/12]
Below are some history commands and the results they
would produce:
history words $ [expr $ageInMonths/12]
history words 1-2{%s is %d years old} Alice
history words *a*o*{%s is %d years old} [expr $ageInMonths/12]
History words results in history revision: see below
for details.
HISTORY REVISION
The history options event, redo, substitute, and words
result in ``history revision''. When one of these options
is invoked then the current event is modified to eliminate
the history command and replace it with the result of the
history command. For example, suppose that the most recent
command in the history list is
set a [expr $b+2]
and suppose that the next command invoked is one of the ones
on the left side of the table below. The command actually
recorded in the history event will be the corresponding one
on the right side of the table.
history redo set a [expr $b+2]
history s a b set b [expr $b+2]
set c [history w 2]set c [expr $b+2]
History revision is needed because event specifiers like -1
are only valid at a particular time: once more events have
been added to the history list a different event specifier
would be needed. History revision occurs even when history
is invoked indirectly from the current event (e.g. a user
types a command that invokes a Tcl procedure that invokes
history): the top-level command whose execution eventually
resulted in a history command is replaced. If you wish to
invoke commands like history words without history revision,
you can use history event to save the current history event
and then use history change to restore it later.
KEYWORDS
event, history, record, revision
_________________________________________________________________
NAME
if - Execute scripts conditionally
SYNOPSIS
if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ...
?else? ?bodyN?
_________________________________________________________________
DESCRIPTION
The if command evaluates expr1 as an expression (in the same
way that expr evaluates its argument). The value of the
expression must be a boolean (a numeric value, where 0 is |
false and anything is true, or a string value such as true |
or yes for true and false or no for false); if it is true
then body1 is executed by passing it to the Tcl interpreter.
Otherwise expr2 is evaluated as an expression and if it is
true then body2 is executed, and so on. If none of the
expressions evaluates to true then bodyN is executed. The
then and else arguments are optional ``noise words'' to make
the command easier to read. There may be any number of
elseif clauses, including zero. BodyN may also be omitted
as long as else is omitted too. The return value from the
command is the result of the body script that was executed,
or an empty string if none of the expressions was non-zero
and there was no bodyN.
KEYWORDS
boolean, conditional, else, false, if, true
_________________________________________________________________
NAME
incr - Increment the value of a variable
SYNOPSIS
incr varName ?increment?
_________________________________________________________________
DESCRIPTION
Increments the value stored in the variable whose name is
varName. The value of the variable must be an integer. If
increment is supplied then its value (which must be an
integer) is added to the value of variable varName; other-
wise 1 is added to varName. The new value is stored as a
decimal string in variable varName and also returned as
result.
KEYWORDS
add, increment, variable, value
_________________________________________________________________
NAME
info - Return information about the state of the Tcl inter-
preter
SYNOPSIS
info option ?arg arg ...?
_________________________________________________________________
DESCRIPTION
This command provides information about various internals of
the Tcl interpreter. The legal option's (which may be
abbreviated) are:
info args procname
Returns a list containing the names of the arguments to
procedure procname, in order. Procname must be the
name of a Tcl command procedure.
info body procname
Returns the body of procedure procname. Procname must
be the name of a Tcl command procedure.
info cmdcount
Returns a count of the total number of commands that
have been invoked in this interpreter.
info commands ?pattern?
If pattern isn't specified, returns a list of names of
all the Tcl commands, including both the built-in com-
mands written in C and the command procedures defined
using the proc command. If pattern is specified, only
those names matching pattern are returned. Matching is
determined using the same rules as for string match.
info complete command
Returns 1 if command is a complete Tcl command in the
sense of having no unclosed quotes, braces, brackets or
array element names, If the command doesn't appear to
be complete then 0 is returned. This command is typi-
cally used in line-oriented input environments to allow
users to type in commands that span multiple lines; if
the command isn't complete, the script can delay
evaluating it until additional lines have been typed to
complete the command.
info default procname arg varname
Procname must be the name of a Tcl command procedure
and arg must be the name of an argument to that pro-
cedure. If arg doesn't have a default value then the
command returns 0. Otherwise it returns 1 and places
the default value of arg into variable varname.
info exists varName
Returns 1 if the variable named varName exists in the
current context (either as a global or local variable),
returns 0 otherwise.
info globals ?pattern?
If pattern isn't specified, returns a list of all the
names of currently-defined global variables. If pat-
tern is specified, only those names matching pattern
are returned. Matching is determined using the same
rules as for string match.
info level ?number?
If number is not specified, this command returns a
number giving the stack level of the invoking pro-
cedure, or 0 if the command is invoked at top-level.
If number is specified, then the result is a list con-
sisting of the name and arguments for the procedure
call at level number on the stack. If number is posi-
tive then it selects a particular stack level (1 refers
to the top-most active procedure, 2 to the procedure it
called, and so on); otherwise it gives a level relative
to the current level (0 refers to the current pro-
cedure, -1 to its caller, and so on). See the uplevel
command for more information on what stack levels mean.
info library
Returns the name of the library directory in which
standard Tcl scripts are stored. The default value for
the library is compiled into Tcl, but it may be over-
ridden by setting the TCL_LIBRARY environment variable.
If there is no TCL_LIBRARY variable and no compiled-in
value then and error is generated. See the library
manual entry for details of the facilities provided by
the Tcl script library. Normally each application will
have its own application-specific script library in
addition to the Tcl script library; I suggest that
each application set a global variable with a name like
$app_library (where app is the application's name) to
hold the location of that application's library direc-
tory.
info locals ?pattern?
If pattern isn't specified, returns a list of all the
names of currently-defined local variables, including
arguments to the current procedure, if any. Variables
defined with the global and upvar commands will not be
returned. If pattern is specified, only those names
matching pattern are returned. Matching is determined
using the same rules as for string match.
info patchlevel
Returns a decimal integer giving the current patch |
level for Tcl. The patch level is incremented for each |
new release or patch, and it uniquely identifies an |
official version of Tcl.
info procs ?pattern?
If pattern isn't specified, returns a list of all the
names of Tcl command procedures. If pattern is speci-
fied, only those names matching pattern are returned.
Matching is determined using the same rules as for
string match.
info script
If a Tcl script file is currently being evaluated (i.e.
there is a call to Tcl_EvalFile active or there is an
active invocation of the source command), then this
command returns the name of the innermost file being
processed. Otherwise the command returns an empty
string.
info tclversion
Returns the version number for this version of Tcl in
the form x.y, where changes to x represent major
changes with probable incompatibilities and changes to
y represent small enhancements and bug fixes that
retain backward compatibility.
info vars ?pattern?
If pattern isn't specified, returns a list of all the
names of currently-visible variables, including both
locals and currently-visible globals. If pattern is
specified, only those names matching pattern are
returned. Matching is determined using the same rules
as for string match.
KEYWORDS
command, information, interpreter, level, procedure, vari-
able
_________________________________________________________________
NAME
join - Create a string by joining together list elements
SYNOPSIS
join list ?joinString?
_________________________________________________________________
DESCRIPTION
The list argument must be a valid Tcl list. This command
returns the string formed by joining all of the elements of
list together with joinString separating each adjacent pair
of elements. The joinString argument defaults to a space
character.
KEYWORDS
element, join, list, separator
_________________________________________________________________
NAME
lappend - Append list elements onto a variable
SYNOPSIS
lappend varName value ?value value ...?
_________________________________________________________________
DESCRIPTION
This command treats the variable given by varName as a list
and appends each of the value arguments to that list as a
separate element, with spaces between elements. If varName
doesn't exist, it is created as a list with elements given
by the value arguments. Lappend is similar to append except
that the values are appended as list elements rather than
raw text. This command provides a relatively efficient way
to build up large lists. For example, ``lappend a $b'' is
much more efficient than ``set a [concat $a [list $b]]''
when $a is long.
KEYWORDS
append, element, list, variable
_________________________________________________________________
NAME
library - standard library of Tcl procedures
SYNOPSIS
auto_execok cmd
auto_load cmd
auto_mkindex dir pattern pattern ...
auto_reset
parray arrayName
unknown cmd ?arg arg ...?
_________________________________________________________________
INTRODUCTION
Tcl includes a library of Tcl procedures for commonly-needed
functions. The procedures defined in the Tcl library are
generic ones suitable for use by many different applica-
tions. The location of the Tcl library is returned by the
info library command. In addition to the Tcl library, each
application will normally have its own library of support
procedures as well; the location of this library is nor-
mally given by the value of the $app_library global vari-
able, where app is the name of the application. For exam-
ple, the location of the Tk library is kept in the variable
$tk_library.
# To access the procedures in the Tcl library, an application
# should source the file init.tcl in the library, for example
# with the Tcl command
#
# source [info library]/init.tcl
# This will define the unknown procedure and arrange for the
# other procedures to be loaded on-demand using the auto-load
# mechanism defined below.
COMMAND PROCEDURES
The following procedures are provided in the Tcl library:
auto_execok cmd
Determines whether there is an executable file by the
name cmd. This command examines the directories in the
current search path (given by the PATH enviornment
variable) to see if there is an executable file named
cmd in any of those directories. If so, it returns 1;
if not it returns 0. Auto_exec remembers information
about previous searches in an array named auto_execs;
this avoids the path search in future calls for the
same cmd. The command auto_reset may be used to force
auto_execok to forget its cached information.
auto_load cmd
This command attempts to load the definition for a Tcl
command named cmd. To do this, it searches an auto-
load path, which is a list of one or more directories.
The auto-load path is given by the global variable
$auto_path if it exists. If there is no $auto_path
variable, then the TCLLIBPATH environment variable is
used, if it exists. Otherwise the auto-load path con-
sists of just the Tcl library directory. Within each
directory in the auto-load path there must be a file
tclIndex that describes one or more commands defined in |
that directory and a script to evaluate to load each of |
the commands. The tclIndex file should be generated |
with the auto_mkindex command. If cmd is found in an |
index file, then the appropriate script is evaluated to |
create the command. The auto_load command returns 1 if
cmd was successfully created. The command returns 0 if
there was no index entry for cmd or if the script
didn't actually define cmd (e.g. because index informa-
tion is out of date). If an error occurs while pro-
cessing the script, then that error is returned.
Auto_load only reads the index information once and
saves it in the array auto_index; future calls to
auto_load check for cmd in the array rather than re-
reading the index files. The cached index information
may be deleted with the command auto_reset. This will
force the next auto_load command to reload the index
database from disk.
auto_mkindex dir pattern pattern ...
Generates an index suitable for use by auto_load. The |
command searches dir for all files whose names match |
any of the pattern arguments (matching is done with the
glob command), generates an index of all the Tcl com-
mand procedures defined in all the matching files, and
stores the index information in a file named tclIndex
in dir. For example, the command
auto_mkindex foo *.tcl
will read all the .tcl files in subdirectory foo and
generate a new index file foo/tclIndex.
Auto_mkindex parses the Tcl scripts in a relatively
unsophisticated way: if any line contains the word
proc as its first characters then it is assumed to be a
procedure definition and the next word of the line is
taken as the procedure's name. Procedure definitions
that don't appear in this way (e.g. they have spaces
before the proc) will not be indexed.
auto_reset
Destroys all the information cached by auto_execok and
auto_load. This information will be re-read from disk
the next time it is needed. Auto_reset also deletes
any procedures listed in the auto-load index, so that
fresh copies of them will be loaded the next time that
they're used.
parray arrayName
Prints on standard output the names and values of all
the elements in the array arrayName. ArrayName must be
an array accessible to the caller of parray. It may be
either local or global.
unknown cmd ?arg arg ...?
This procedure is invoked automatically by the Tcl
interpreter whenever the name of a command doesn't
exist. The unknown procedure receives as its arguments
the name and arguments of the missing command. Unknown |
first calls auto_load to load the command. If this
succeeds, then it executes the original command with
its original arguments. If the auto-load fails then
unknown calls auto_execok to see if there is an execut-
able file by the name cmd. If so, it invokes the Tcl
exec command with cmd and all the args as arguments.
If cmd can't be auto-executed, unknown checks to see if
the command was invoked at top-level and outside of any
script. If so, then unknown takes takes two additional
steps. First, it sees if cmd has one of the following
three forms: !!, !event, or ^old^new?^?. If so, then
unknown carries out history substitution in the same
way that csh would for these constructs. Second, and
last, unknown checks to see if cmd is a unique abbrevi-
ation for an existing Tcl command. If so, it expands
the command name and executes the command with the ori-
ginal arguments. If none of the above efforts has been
able to execute the command, unknown generates an error
return. If the global variable auto_noload is defined,
then the auto-load step is skipped. If the global
variable auto_noexec is defined then the auto-exec step
is skipped. Under normal circumstances the return
value from unknown is the return value from the command
that was eventually executed.
VARIABLES
The following global variables are defined or used by the
procedures in the Tcl library:
auto_execs
Used by auto_execok to record information about whether
particular commands exist as executable files.
auto_index
Used by auto_load to save the index information read
from disk.
auto_noexec
If set to any value, then unknown will not attempt to
auto-exec any commands.
auto_noload
If set to any value, then unknown will not attempt to
auto-load any commands.
auto_path
If set, then it must contain a valid Tcl list giving
directories to search during auto-load operations.
env(TCL_LIBRARY)
If set, then it specifies the location of the directory
containing library scripts (the value of this variable
will be returned by the command info library). If this
variable isn't set then a default value is used.
env(TCLLIBPATH)
If set, then it must contain a valid Tcl list giving
directories to search during auto-load operations.
This variable is only used if auto_path is not defined.
unknown_active
This variable is set by unknown to indicate that it is
active. It is used to detect errors where unknown
recurses on itself infinitely. The variable is unset
before unknown returns.
KEYWORDS
auto-exec, auto-load, library, unknown
_________________________________________________________________
NAME
lindex - Retrieve an element from a list
SYNOPSIS
lindex list index
_________________________________________________________________
DESCRIPTION
This command treats list as a Tcl list and returns the
index'th element from it (0 refers to the first element of
the list). In extracting the element, lindex observes the
same rules concerning braces and quotes and backslashes as
the Tcl command interpreter; however, variable substitution
and command substitution do not occur. If index is negative
or greater than or equal to the number of elements in value,
then an empty string is returned.
KEYWORDS
element, index, list
_________________________________________________________________
NAME
linsert - Insert elements into a list
SYNOPSIS
linsert list index element ?element element ...?
_________________________________________________________________
DESCRIPTION
This command produces a new list from list by inserting all
of the element arguments just before the indexth element of
list. Each element argument will become a separate element
of the new list. If index is less than or equal to zero,
then the new elements are inserted at the beginning of the
list. If index is greater than or equal to the number of
elements in the list, then the new elements are appended to
the list.
KEYWORDS
element, insert, list
_________________________________________________________________
NAME
list - Create a list
SYNOPSIS
list ?arg arg ...? |
_________________________________________________________________
DESCRIPTION
This command returns a list comprised of all the args, or an |
empty string if no args are specified. Braces and
backslashes get added as necessary, so that the index com-
mand may be used on the result to re-extract the original
arguments, and also so that eval may be used to execute the
resulting list, with arg1 comprising the command's name and
the other args comprising its arguments. List produces
slightly different results than concat: concat removes one
level of grouping before forming the list, while list works
directly from the original arguments. For example, the com-
mand
list a b {c d e} {f {g h}}
will return
a b {c d e} {f {g h}}
while concat with the same arguments will return
a b c d e f {g h}
KEYWORDS
element, list
_________________________________________________________________
NAME
llength - Count the number of elements in a list
SYNOPSIS
llength list
_________________________________________________________________
DESCRIPTION
Treats list as a list and returns a decimal string giving
the number of elements in it.
KEYWORDS
element, list, length
_________________________________________________________________
NAME
lrange - Return one or more adjacent elements from a list
SYNOPSIS
lrange list first last
_________________________________________________________________
DESCRIPTION
List must be a valid Tcl list. This command will return a
new list consisting of elements first through last,
inclusive. Last may be end (or any abbreviation of it) to
refer to the last element of the list. If first is less
than zero, it is treated as if it were zero. If last is
greater than or equal to the number of elements in the list,
then it is treated as if it were end. If first is greater
than last then an empty string is returned. Note: ``lrange
list first first'' does not always produce the same result
as ``lindex list first'' (although it often does for simple
fields that aren't enclosed in braces); it does, however,
produce exactly the same results as ``list [lindex list
first]''
KEYWORDS
element, list, range, sublist
_________________________________________________________________
NAME
lreplace - Replace elements in a list with new elements
SYNOPSIS
lreplace list first last ?element element ...?
_________________________________________________________________
DESCRIPTION
Lreplace returns a new list formed by replacing one or more
elements of list with the element arguments. First gives
the index in list of the first element to be replaced. If
first is less than zero then it refers to the first element
of list; the element indicated by first must exist in the
list. Last gives the index in list of the last element to
be replaced; it must be greater than or equal to first.
Last may be end (or any abbreviation of it) to indicate that
all elements between first and the end of the list should be
replaced. The element arguments specify zero or more new
arguments to be added to the list in place of those that
were deleted. Each element argument will become a separate
element of the list. If no element arguments are specified,
then the elements between first and last are simply deleted.
KEYWORDS
element, list, replace
_________________________________________________________________
NAME
lsearch - See if a list contains a particular element
SYNOPSIS
lsearch ?mode? list pattern
_________________________________________________________________
DESCRIPTION
This command searches the elements of list to see if one of
them matches pattern. If so, the command returns the index
of the first matching element. If not, the command returns
-1. The mode argument indicates how the elements of the |
list are to be matched against pattern and it must have one |
of the following values: |
-exact ||
The list element must contain exactly the same string |
as pattern. |
-glob ||
Pattern is a glob-style pattern which is matched |
against each list element using the same rules as the |
string match command. |
-regexp ||
Pattern is treated as a regular expression and matched |
against each list element using the same rules as the |
regexp command. |
If mode is omitted then it defaults to -glob.
KEYWORDS
list, match, pattern, regular expression, search, string
_________________________________________________________________
NAME
lsort - Sort the elements of a list
SYNOPSIS
lsort ?switches? list
_________________________________________________________________
DESCRIPTION
This command sorts the elements of list, returning a new
list in sorted order. By default ASCII sorting is used with
the result returned in increasing order. However, any of |
the following switches may be specified before list to con- |
trol the sorting process (unique abbreviations are |
accepted): |
-ascii ||
Use string comparison with ASCII colla- |
tion order. This is the default. |
-ignore ||
ASCII comparison, ignore case.
-integer ||
Convert list elements to integers and |
use integer comparison. |
-real ||
Convert list elements to floating-point |
values and use floating comparison. |
-command command ||
Use command as a comparison command. To |
compare two elements, evaluate a Tcl |
script consisting of command with the |
two elements appended as additional |
arguments. The script should return an |
integer less than, equal to, or greater |
than zero if the first element is to be |
considered less than, equal to, or |
greater than the second, respectively. |
-increas- |
ing ||
Sort the list in increasing order |
(``smallest'' items first). This is the |
default. |
-decreas- |
ing ||
Sort the list in decreasing order |
(``largest'' items first).
KEYWORDS
element, list, order, sort
_________________________________________________________________
NAME
open - Open a file
SYNOPSIS
open fileName ?access? ?permissions? |
_________________________________________________________________
DESCRIPTION
This command opens a file and returns an identifier that may
be used in future invocations of commands like read, puts,
and close. FileName gives the name of the file to open; if
it starts with a tilde then tilde substitution is performed
as described for Tcl_TildeSubst. If the first character of
fileName is ``|'' then the remaining characters of fileName
are treated as a command pipeline to invoke, in the same
style as for exec. In this case, the identifier returned by
open may be used to write to the command's input pipe or
read from its output pipe.
The access argument indicates the way in which the file (or
command pipeline) is to be accessed. It may take two forms, |
either a string in the form that would be passed to the |
fopen library procedure or a list of POSIX access flags. It |
defaults to ``r''. In the first form access may have any of |
the following values:
r Open the file for reading only; the file must
already exist.
r+ Open the file for both reading and writing;
the file must already exist.
w Open the file for writing only. Truncate it
if it exists. If it doesn't exist, create a
new file.
w+ Open the file for reading and writing. Trun-
cate it if it exists. If it doesn't exist,
create a new file.
a Open the file for writing only. The file
must already exist, and the file is posi-
tioned so that new data is appended to the
file.
a+ Open the file for reading and writing. If
the file doesn't exist, create a new empty
file. Set the initial access position to
the end of the file.
In the second form, access consists of a list of any of the |
following flags, all of which have the standard POSIX mean- |
ings. One of the flags must be either RDONLY, WRONLY or |
RDWR. |
RDONLY ||
Open the file for reading only. |
WRONLY ||
Open the file for writing only. |
RDWR ||
Open the file for both reading and writing. |
APPEND ||
Set the file pointer to the end of the file |
prior to each write. |
CREAT ||
Create the file if it doesn't already exist |
(without this flag it is an error for the |
file not to exist). |
EXCL ||
If CREAT is specified also, an error is |
returned if the file already exists. |
NOCTTY ||
If the file is a terminal device, this flag |
prevents the file from becoming the control- |
ling terminal of the process. |
NON- |
BLOCK ||
Prevents the process from blocking while |
opening the file. For details refer to your |
system documentation on the open system |
call's O_NONBLOCK flag. |
TRUNC ||
If the file exists it is truncated to zero |
length. |
If a new file is created as part of opening it, permissions |
(an integer) is used to set the permissions for the new file |
in conjunction with the process's file mode creation mask. |
Permissions defaults to 0666.
If a file is opened for both reading and writing then seek
must be invoked between a read and a write, or vice versa
(this restriction does not apply to command pipelines opened
with open). When fileName specifies a command pipeline and
a write-only access is used, then standard output from the
pipeline is directed to the current standard output unless
overridden by the command. When fileName specifies a com-
mand pipeline and a read-only access is used, then standard
input from the pipeline is taken from the current standard
input unless overridden by the command.
KEYWORDS
access mode, append, controlling terminal, create, file,
non-blocking, open, permissions, pipeline, process
_________________________________________________________________
NAME
pid - Retrieve process id(s)
SYNOPSIS
pid ?fileId?
_________________________________________________________________
DESCRIPTION
If the fileId argument is given then it should normally
refer to a process pipeline created with the open command.
In this case the pid command will return a list whose ele-
ments are the process identifiers of all the processes in
the pipeline, in order. The list will be empty if fileId
refers to an open file that isn't a process pipeline. If no
fileId argument is given then pid returns the process iden-
tifier of the current process. All process identifiers are
returned as decimal strings.
KEYWORDS
file, pipeline, process identifier
_________________________________________________________________
NAME
proc - Create a Tcl procedure
SYNOPSIS
proc name args body
_________________________________________________________________
DESCRIPTION
The proc command creates a new Tcl procedure named name,
replacing any existing command or procedure there may have
been by that name. Whenever the new command is invoked, the
contents of body will be executed by the Tcl interpreter.
Args specifies the formal arguments to the procedure. It
consists of a list, possibly empty, each of whose elements
specifies one argument. Each argument specifier is also a
list with either one or two fields. If there is only a sin-
gle field in the specifier then it is the name of the argu-
ment; if there are two fields, then the first is the argu-
ment name and the second is its default value.
When name is invoked a local variable will be created for
each of the formal arguments to the procedure; its value
will be the value of corresponding argument in the invoking
command or the argument's default value. Arguments with
default values need not be specified in a procedure invoca-
tion. However, there must be enough actual arguments for
all the formal arguments that don't have defaults, and there
must not be any extra actual arguments. There is one spe-
cial case to permit procedures with variable numbers of
arguments. If the last formal argument has the name args,
then a call to the procedure may contain more actual argu-
ments than the procedure has formals. In this case, all of
the actual arguments starting at the one that would be
assigned to args are combined into a list (as if the list
command had been used); this combined value is assigned to
the local variable args.
When body is being executed, variable names normally refer
to local variables, which are created automatically when
referenced and deleted when the procedure returns. One
local variable is automatically created for each of the
procedure's arguments. Global variables can only be
accessed by invoking the global command or the upvar com-
mand.
The proc command returns an empty string. When a procedure
is invoked, the procedure's return value is the value speci-
fied in a return command. If the procedure doesn't execute
an explicit return, then its return value is the value of
the last command executed in the procedure's body. If an
error occurs while executing the procedure body, then the
procedure-as-a-whole will return that same error.
KEYWORDS
argument, procedure
_________________________________________________________________
NAME
puts - Write to a file
SYNOPSIS
puts ?-nonewline? fileId string
_________________________________________________________________
DESCRIPTION
Writes the characters given by string to the file given by
fileId. FileId must have been the return value from a pre-
vious call to open; it must refer to a file that was opened
for writing. Puts normally outputs a newline
character after string, but this feature may be suppressed
by specifying the -nonewline switch. Output to files is
buffered internally by Tcl; the flush command may be used to
force buffered characters to be output.
Note that <stdout> is not supported in Alpha!
KEYWORDS
file, newline, output, write
_________________________________________________________________
NAME
pwd - Return the current working directory
SYNOPSIS
pwd
_________________________________________________________________
DESCRIPTION
Returns the path name of the current working directory.
KEYWORDS
working directory
_________________________________________________________________
NAME
read - Read from a file
SYNOPSIS
read ?-nonewline? fileId
read fileId numBytes
_________________________________________________________________
DESCRIPTION
In the first form, all of the remaining bytes are read from
the file given by fileId; they are returned as the result of
the command. If the -nonewline switch is specified then the
last character of the file is discarded if it is a newline.
In the second form, the extra argument specifies how many
bytes to read; exactly this many bytes will be read and
returned, unless there are fewer than numBytes bytes left in
the file; in this case, all the remaining bytes are
returned. FileId must be stdin or the return value from a
previous call to open; it must refer to a file that was
opened for reading. Any existing end-of-file or error con- |
dition on the file is cleared at the beginning of the read |
command.
KEYWORDS
file, read
_________________________________________________________________
NAME
regexp - Match a regular expression against a string
SYNOPSIS
regexp ?switches? exp string ?matchVar? ?subMatchVar sub-
MatchVar ...?
_________________________________________________________________
DESCRIPTION
Determines whether the regular expression exp matches part
or all of string and returns 1 if it does, 0 if it doesn't.
If additional arguments are specified after string then they
are treated as the names of variables in which to return
information about which part(s) of string matched exp.
MatchVar will be set to the range of string that matched all
of exp. The first subMatchVar will contain the characters
in string that matched the leftmost parenthesized subexpres-
sion within exp, the next subMatchVar will contain the char-
acters that matched the next parenthesized subexpression to
the right in exp, and so on.
If the initial arguments to regexp start with - then they |
are treated as switches. The following switches are |
currently supported: |
-nocase ||
Causes upper-case characters in string to be |
treated as lower case during the matching process. |
-indices ||
Changes what is stored in the subMatchVars. |
Instead of storing the matching characters from |
string, each variable will contain a list of two |
decimal strings giving the indices in string of |
the first and last characters in the matching |
range of characters. |
-- ||
Marks the end of switches. The argument following |
this one will be treated as exp even if it starts |
with a -.
If there are more subMatchVar's than parenthesized subex-
pressions within exp, or if a particular subexpression in
exp doesn't match the string (e.g. because it was in a por-
tion of the expression that wasn't matched), then the
corresponding subMatchVar will be set to ``-1 -1'' if
-indices has been specified or to an empty string otherwise.
REGULAR EXPRESSIONS
Regular expressions are implemented using Henry Spencer's
package (thanks, Henry!), and much of the description of
regular expressions below is copied verbatim from his manual
entry.
A regular expression is zero or more branches, separated by
``|''. It matches anything that matches one of the
branches.
A branch is zero or more pieces, concatenated. It matches a
match for the first, followed by a match for the second,
etc.
A piece is an atom possibly followed by ``*'', ``+'', or
``?''. An atom followed by ``*'' matches a sequence of 0 or
more matches of the atom. An atom followed by ``+'' matches
a sequence of 1 or more matches of the atom. An atom fol-
lowed by ``?'' matches a match of the atom, or the null
string.
An atom is a regular expression in parentheses (matching a
match for the regular expression), a range (see below),
``.'' (matching any single character), ``^'' (matching the
null string at the beginning of the input string), ``$''
(matching the null string at the end of the input string), a
``\'' followed by a single character (matching that charac-
ter), or a single character with no other significance
(matching that character).
A range is a sequence of characters enclosed in ``[]''. It
normally matches any single character from the sequence. If
the sequence begins with ``^'', it matches any single char-
acter not from the rest of the sequence. If two characters
in the sequence are separated by ``-'', this is shorthand
for the full list of ASCII characters between them (e.g.
``[0-9]'' matches any decimal digit). To include a literal
``]'' in the sequence, make it the first character (follow-
ing a possible ``^''). To include a literal ``-'', make it
the first or last character.
CHOOSING AMONG ALTERNATIVE MATCHES
In general there may be more than one way to match a regular
expression to an input string. For example, consider the
command
regexp (a*)b* aabaaabb x y
Considering only the rules given so far, x and y could end
up with the values aabb and aa, aaab and aaa, ab and a, or
any of several other combinations. To resolve this poten-
tial ambiguity regexp chooses among alternatives using the
rule ``first then longest''. In other words, it consders
the possible matches in order working from left to right
across the input string and the pattern, and it attempts to
match longer pieces of the input string before shorter ones.
More specifically, the following rules apply in decreasing
order of priority:
[1] If a regular expression could match two different parts
of an input string then it will match the one that
begins earliest.
[2] If a regular expression contains | operators then the
leftmost matching sub-expression is chosen.
[3] In *, +, and ? constructs, longer matches are chosen in
preference to shorter ones.
[4] In sequences of expression components the components
are considered from left to right.
In the example from above, (a*)b* matches aab: the (a*)
portion of the pattern is matched first and it consumes the
leading aa; then the b* portion of the pattern consumes the
next b. Or, consider the following example:
regexp (ab|a)(b*)c abc x y z
After this command x will be abc, y will be ab, and z will
be an empty string. Rule 4 specifies that (ab|a) gets first
shot at the input string and Rule 2 specifies that the ab
sub-expression is checked before the a sub-expression. Thus
the b has already been claimed before the (b*) component is
checked and (b*) must match an empty string.
KEYWORDS
match, regular expression, string
_________________________________________________________________
NAME
regsub - Perform substitutions based on regular expression
pattern matching
SYNOPSIS
regsub ?switches? exp string subSpec varName
_________________________________________________________________
DESCRIPTION
This command matches the regular expression exp against
string, and it copies string to the variable whose name is |
given by varName. The command returns 1 if there is a match |
and 0 if there isn't. If there is a match, then while copy- |
ing string to varName the portion of string that matched exp
is replaced with subSpec. If subSpec contains a ``&'' or
``\0'', then it is replaced in the substitution with the
portion of string that matched exp. If subSpec contains a
``\n'', where n is a digit between 1 and 9, then it is
replaced in the substitution with the portion of string that
matched the n-th parenthesized subexpression of exp. Addi-
tional backslashes may be used in subSpec to prevent special
interpretation of ``&'' or ``\0'' or ``\n'' or backslash.
The use of backslashes in subSpec tends to interact badly
with the Tcl parser's use of backslashes, so it's generally
safest to enclose subSpec in braces if it includes
backslashes.
If the initial arguments to regexp start with - then they |
are treated as switches. The following switches are |
currently supported: |
-all ||
All ranges in string that match exp are found and |
substitution is performed for each of these |
ranges. Without this switch only the first match- |
ing range is found and substituted. If -all is |
specified, then ``&'' and ``\n'' sequences are |
handled for each substitution using the informa- |
tion from the corresponding match. |
-nocase ||
Upper-case characters in string will be converted |
to lower-case before matching against exp; how- |
ever, substitutions specified by subSpec use the |
original unconverted form of string. |
-- ||
Marks the end of switches. The argument following |
this one will be treated as exp even if it starts |
with a -.
See the manual entry for regexp for details on the interpre-
tation of regular expressions.
KEYWORDS
match, pattern, regular expression, substitute
_________________________________________________________________
NAME
rename - Rename or delete a command
SYNOPSIS
rename oldName newName
_________________________________________________________________
DESCRIPTION
Rename the command that used to be called oldName so that it
is now called newName. If newName is an empty string then
oldName is deleted. The rename command returns an empty
string as result.
KEYWORDS
command, delete, rename
_________________________________________________________________
NAME
return - Return from a procedure
SYNOPSIS
return ?-code code? ?-errorinfo info? ?-errorcode code?
?string?
_________________________________________________________________
DESCRIPTION
Return immediately from the current procedure (or top-level
command or source command), with string as the return value.
If string is not specified then an empty string will be
returned as result.
EXCEPTIONAL RETURNS
In the usual case where the -code option isn't specified the |
procedure will return normally (its completion code will be |
TCL_OK). However, the -code option may be used to generate |
an exceptional return from the procedure. Code may have any |
of the following values: |
ok ||
Normal return: same as if the option is omitted. |
error ||
Error return: same as if the error command were |
used to terminate the procedure, except for han- |
dling of errorInfo and errorCode variables (see |
below). |
return ||
The current procedure will return with a comple- |
tion code of TCL_RETURN, so that the procedure |
that invoked it will return also. |
break ||
The current procedure will return with a comple- |
tion code of TCL_BREAK, which will terminate the |
innermost nested loop in the code that invoked the |
current procedure. |
con- |
tinue ||
The current procedure will return with a comple- |
tion code of TCL_CONTINUE, which will terminate |
the current iteration of the innermost nested loop |
in the code that invoked the current procedure. |
value ||
Value must be an integer; it will be returned as |
the completion code for the current procedure. |
The -code option is rarely used. It is provided so that |
procedures that implement new control structures can reflect |
exceptional conditions back to their callers. |
Two additional options, -errorinfo and -errorcode, may be |
used to provide additional information during error returns. |
These options are ignored unless code is error. |
The -errorinfo option specifies an initial stack trace for |
the errorInfo variable; if it is not specified then the |
stack trace left in errorInfo will include the call to the |
procedure and higher levels on the stack but it will not |
include any information about the context of the error |
within the procedure. Typically the info value is supplied |
from the value left in errorInfo after a catch command |
trapped an error within the procedure. |
If the -errorcode option is specified then code provides a |
value for the errorCode variable. If the option is not |
specified then errorCode will default to NONE.
KEYWORDS
break, continue, error, procedure, return
_________________________________________________________________
NAME
scan - Parse string using conversion specifiers in the style
of sscanf
SYNOPSIS
scan string format varName ?varName ...?
_________________________________________________________________
INTRODUCTION
This command parses fields from an input string in the same
fashion as the ANSI C sscanf procedure and returns a count
of the number of fields sucessfully parsed. String gives
the input to be parsed and format indicates how to parse it,
using % conversion specifiers as in sscanf. Each varName
gives the name of a variable; when a field is scanned from
string the result is converted back into a string and
assigned to the corresponding variable.
DETAILS ON SCANNING
Scan operates by scanning string and formatString together.
If the next character in formatString is a blank or tab then
it is ignored. Otherwise, if it isn't a % character then it
must match the next non-white-space character of string.
When a % is encountered in formatString, it indicates the
start of a conversion specifier. A conversion specifier
contains three fields after the %: a *, which indicates that
the converted value is to be discarded instead of assigned
to a variable; a number indicating a maximum field width;
and a conversion character. All of these fields are
optional except for the conversion character.
When scan finds a conversion specifier in formatString, it
first skips any white-space characters in string. Then it
converts the next input characters according to the conver-
sion specifier and stores the result in the variable given
by the next argument to scan. The following conversion
characters are supported:
d The input field must be a decimal integer. It is
read in and the value is stored in the variable as
a decimal string.
o The input field must be an octal integer. It is
read in and the value is stored in the variable as
a decimal string.
x The input field must be a hexadecimal integer. It
is read in and the value is stored in the variable
as a decimal string.
c A single character is read in and its binary value
is stored in the variable as a decimal string.
Initial white space is not skipped in this case,
so the input field may be a white-space character.
This conversion is different from the ANSI stan-
dard in that the input field always consists of a
single character and no field width may be speci-
fied.
s The input field consists of all the characters up
to the next white-space character; the characters
are copied to the variable.
e or f or g
The input field must be a floating-point number
consisting of an optional sign, a string of
decimal digits possibly con taining a decimal
point, and an optional exponent consisting of an e
or E followed by an optional sign and a string of
decimal digits. It is read in and stored in the
variable as a floating-point string.
[chars] The input field consists of any number of charac-
ters in chars. The matching string is stored in
the variable. If the first character between the
brackets is a ] then it is treated as part of
chars rather than the closing bracket for the set.
[^chars] The input field consists of any number of charac-
ters not in chars. The matching string is stored
in the variable. If the character immediately
following the ^ is a ] then it is treated as part
of the set rather than the closing bracket for the
set.
The number of characters read from the input for a conver-
sion is the largest number that makes sense for that partic-
ular conversion (e.g. as many decimal digits as possible
for %d, as many octal digits as possible for %o, and so on).
The input field for a given conversion terminates either
when a white-space character is encountered or when the max-
imum field width has been reached, whichever comes first.
If a * is present in the conversion specifier then no vari-
able is assigned and the next scan argument is not consumed.
DIFFERENCES FROM ANSI SSCANF
The behavior of the scan command is the same as the behavior
of the ANSI C sscanf procedure except for the following
differences:
[1] %p and %n conversion specifiers are not currently sup- |
ported.
[2] For %c conversions a single character value is con-
verted to a decimal string, which is then assigned to
the corresponding varName; no field width may be speci-
fied for this conversion.
[3] The l, h, and L modifiers are ignored; integer values |
are always converted as if there were no modifier |
present and real values are always converted as if the |
l modifier were present (i.e. type double is used for |
the internal representation).
KEYWORDS
conversion specifier, parse, scan
FILE SCANNING COMMANDS
These commands provide a facility to scan files, matching
lines of the file against regular expressions and executing
Tcl code on a match. With this facility you can use Tcl to
do the sort of file processing that is traditionally done
with awk. And since Tcl's approach is more declarative,
some of the scripts that can be rather difficult to write in
awk are simple to code in Tcl.
File scanning in Tcl centers around the concept of a scan
context. A scan context contains one or more match state-
ments, which associate regular expressions to scan for with
Tcl code to be executed when the expressions are matched.
scancontext ?option?
This command manages file scan contexts. A scan con-
text is a collection of regular expressions and com-
mands to execute when that regular expression matches a
line of the file. A context may also have a single
default match, to be applied against lines that do not
match any of the regular expressions. Multiple scan
contexts may be defined and they may be reused on mul-
tiple files. A scan context is identified by a context
handle. The scancontext command takes the following
forms:
scancontext create
Create a new scan context. The scanmatch command is
used to define patterns in the context. A contexthan-
dle is returned, which the Tcl programmer uses to refer
to the newly created scan context in calls to the Tcl
file scanning commands.
scancontext delete contexthandle
Delete the scan context identified by contexthandle,
and free all of the match statements and compiled regu-
lar expressions associated with the specified context.
scanfile ?-copyfile copyFileId? contexthandle fileId
Scan the file specified by fileId, starting from the
current file position. Check all patterns in the scan
context specified by contexthandle against it, execut-
ing the match commands corresponding to patterns
matched.
If the optional -copyfile argument is specified, the
next argument is a file ID to which all lines not
matched by any pattern (excluding the default pattern)
are to be written.
scanmatch ?-nocase? contexthandle ?regexp? commands
Specify Tcl commands, to be evaluated when regexp is
matched by a scanfile command. The match is added to
the scan context specified by contexthandle. Any
number of match statements may be specified for a give
context. Regexp is a regular expression (see the
regexp command). If -nocase is specified as the first
argument, the pattern is matched regardless of alpha-
betic case.
If regexp is not specified, then a default match is
specified for the scan context. The default match will
be executed when a line of the file does not match any
of the regular expressions in the current scancontext.
The array matchInfo is available to the Tcl code that
is executed when an expression matches (or defaults).
It contans information about the file being scanned and
where within it the expression was matched.
matchInfo is local to the top level of the match com-
mand unless declared global at that level by the Tcl
global command. If it is to be used as a global, it
must be declared global before scanfile is called
(since scanfile sets the matchInfo before the match
code is executed, a subsequent global will override the
local variable). The following array entries are
available:
matchInfo(line)
Contains the text of the line of the file that was
matched.
matchInfo(offset)
The byte offset into the file of the first charac-
ter of the line that was matched.
matchInfo(linenum)
The line number of the line that was matched. This
is relative to the first line scanned, which is
usually, but not necessarily, the first line of
the file. The first line is line number one.
matchInfo(handle)
The file id (handle) of the file currently being
scanned.
matchInfo(copyHandle)
The file id (handle) of the file specified by the
-copyfile option. The element does not exist if
-copyfile was not specified.
matchInfo(submatch0)
Will contain the characters matching the first
parenthesized subexpression. The second will be
contained in submatch1, etc.
matchInfo(subindex0)
Will contain the a list of the starting and ending
indices of the string matching the first
parenthesized subexpression. The second will be
contained in subindex1, etc.
All scanmatch patterns that match a line will be processed
in the order in which their specifications were added to the
scan context. The remainder of the scanmatch pattern-
command pairs may be skipped for a file line if a continue
is executed by the Tcl code of a preceding, matched pattern.
If a return is executed in the body of the match command,
the scanfile command currently in progress returns, with the
value passed to return as its return value.
_________________________________________________________________
NAME
seek - Change the access position for an open file
SYNOPSIS
seek fileId offset ?origin?
_________________________________________________________________
DESCRIPTION
Change the current access position for fileId. FileId must
have been the return value from a previous call to open, or
it may be stdin, stdout, or stderr to refer to one of the
standard I/O channels. The offset and origin arguments
specify the position at which the next read or write will
occur for fileId. Offset must be an integer (which may be
negative) and origin must be one of the following:
start
The new access position will be offset bytes from the
start of the file.
current
The new access position will be offset bytes from the
current access position; a negative offset moves the
access position backwards in the file.
end The new access position will be offset bytes from the
end of the file. A negative offset places the access
position before the end-of-file, and a positive offset
places the access position after the end-of-file.
The origin argument defaults to start. This command returns
an empty string.
KEYWORDS
access position, file, seek
_________________________________________________________________
NAME
set - Read and write variables
SYNOPSIS
set varName ?value?
_________________________________________________________________
DESCRIPTION
Returns the value of variable varName. If value is speci-
fied, then set the value of varName to value, creating a new
variable if one doesn't already exist, and return its value.
If varName contains an open parenthesis and ends with a
close parenthesis, then it refers to an array element: the
characters before the first open parenthesis are the name of
the array, and the characters between the parentheses are
the index within the array. Otherwise varName refers to a
scalar variable. If no procedure is active, then varName
refers to a global variable. If a procedure is active, then
varName refers to a parameter or local variable of the pro-
cedure unless the global command has been invoked to declare
varName to be global.
KEYWORDS
read, write, variable
_________________________________________________________________
NAME
source - Evaluate a file as a Tcl script
SYNOPSIS
source fileName
_________________________________________________________________
DESCRIPTION
Read file fileName and pass the contents to the Tcl inter-
preter as a script to evaluate in the normal fashion. The
return value from source is the return value of the last
command executed from the file. If an error occurs in
evaluating the contents of the file then the source command
will return that error. If a return command is invoked from
within the file then the remainder of the file will be
skipped and the source command will return normally with the
result from the return command. If fileName starts with a
tilde, then it is tilde-substituted as described in the
Tcl_TildeSubst manual entry.
KEYWORDS
file, script
_________________________________________________________________
NAME
split - Split a string into a proper Tcl list
SYNOPSIS
split string ?splitChars?
_________________________________________________________________
DESCRIPTION
Returns a list created by splitting string at each character
that is in the splitChars argument. Each element of the
result list will consist of the characters from string that
lie between instances of the characters in splitChars.
Empty list elements will be generated if string contains
adjacent characters in splitChars, or if the first or last
character of string is in splitChars. If splitChars is an
empty string then each character of string becomes a
separate element of the result list. SplitChars defaults to
the standard white-space characters. For example,
split "comp.unix.misc" .
returns "comp unix misc" and
split "Hello world" {}
returns "H e l l o { } w o r l d".
KEYWORDS
list, split, string
_________________________________________________________________
NAME
string - Manipulate strings
SYNOPSIS
string option arg ?arg ...?
_________________________________________________________________
DESCRIPTION
Performs one of several string operations, depending on
option. The legal options (which may be abbreviated) are:
string compare string1 string2
Perform a character-by-character comparison of strings
string1 and string2 in the same way as the C strcmp
procedure. Return -1, 0, or 1, depending on whether
string1 is lexicographically less than, equal to, or
greater than string2.
string first string1 string2
Search string2 for a sequence of characters that
exactly match the characters in string1. If found,
return the index of the first character in the first
such match within string2. If not found, return -1.
string index string charIndex
Returns the charIndex'th character of the string argu-
ment. A charIndex of 0 corresponds to the first char-
acter of the string. If charIndex is less than 0 or
greater than or equal to the length of the string then
an empty string is returned.
string last string1 string2
Search string2 for a sequence of characters that
exactly match the characters in string1. If found,
return the index of the first character in the last
such match within string2. If there is no match, then
return -1.
string length string
Returns a decimal string giving the number of charac-
ters in string.
string match pattern string
See if pattern matches string; return 1 if it does, 0
if it doesn't. Matching is done in a fashion similar
to that used by the C-shell. For the two strings to
match, their contents must be identical except that the
following special sequences may appear in pattern:
* Matches any sequence of characters in string,
including a null string.
? Matches any single character in string.
[chars] Matches any character in the set given by
chars. If a sequence of the form x-y appears
in chars, then any character between x and y,
inclusive, will match.
\x Matches the single character x. This pro-
vides a way of avoiding the special interpre-
tation of the characters *?[]\ in pattern.
string range string first last
Returns a range of consecutive characters from string,
starting with the character whose index is first and
ending with the character whose index is last. An
index of 0 refers to the first character of the string.
Last may be end (or any abbreviation of it) to refer to
the last character of the string. If first is less
than zero then it is treated as if it were zero, and if
last is greater than or equal to the length of the
string then it is treated as if it were end. If first
is greater than last then an empty string is returned.
string tolower string
Returns a value equal to string except that all upper
case letters have been converted to lower case.
string toupper string
Returns a value equal to string except that all lower
case letters have been converted to upper case.
string trim string ?chars?
Returns a value equal to string except that any leading
or trailing characters from the set given by chars are
removed. If chars is not specified then white space is
removed (spaces, tabs, newlines, and carriage returns).
string trimleft string ?chars?
Returns a value equal to string except that any leading
characters from the set given by chars are removed. If
chars is not specified then white space is removed
(spaces, tabs, newlines, and carriage returns).
string trimright string ?chars?
Returns a value equal to string except that any trail-
ing characters from the set given by chars are removed.
If chars is not specified then white space is removed
(spaces, tabs, newlines, and carriage returns).
KEYWORDS
case conversion, compare, index, match, pattern, string
_________________________________________________________________
NAME
switch - Evaluate one of several scripts, depending on a
given value
SYNOPSIS
switch ?options? string pattern body ?pattern body ...?
switch ?options? string {pattern body ?pattern body ...?}
_________________________________________________________________
DESCRIPTION
The switch command matches its string argument against each
of the pattern arguments in order. As soon as it finds a
pattern that matches string it evaluates the following body
argument by passing it recursively to the Tcl interpreter
and returns the result of that evaluation. If the last pat-
tern argument is default then it matches anything. If no
pattern argument matches string and no default is given,
then the switch command returns an empty string.
If the initial arguments to switch start with - then they
are treated as options. The following options are currently
supported:
-exact Use exact matching when comparing string to a pat-
tern. This is the default.
-glob When matching string to the patterns, use glob-
style matching (i.e. the same as implemented by
the string match command).
-regexp When matching string to the patterns, use regular
expression matching (i.e. the same as implemented
by the regexp command).
-- Marks the end of options. The argument following
this one will be treated as string even if it
starts with a -.
Two syntaxes are provided for the pattern and body argu-
ments. The first uses a separate argument for each of the
patterns and commands; this form is convenient if substitu-
tions are desired on some of the patterns or commands. The
second form places all of the patterns and commands together
into a single argument; the argument must have proper list
structure, with the elements of the list being the patterns
and commands. The second form makes it easy to construct
multi-line switch commands, since the braces around the
whole list make it unnecessary to include a backslash at the
end of each line. Since the pattern arguments are in braces
in the second form, no command or variable substitutions are
performed on them; this makes the behavior of the second
form different than the first form in some cases.
If a body is specified as ``-'' it means that the body for
the next pattern should also be used as the body for this
pattern (if the next pattern also has a body of ``-'' then
the body after that is used, and so on). This feature makes
it possible to share a single body among several patterns.
Below are some examples of switch commands:
switch abc a - b {format 1} abc {format 2} default {format 3}
will return 2,
switch -regexp aaab {
^a.*b$ -
b {format 1}
a* {format 2}
default {format 3}
}
will return 1, and
switch xyz {
a
-
b
{format 1}
a*
{format 2}
default
{format 3}
}
will return 3.
KEYWORDS
switch, match, regular expression
_________________________________________________________________
NAME
tclvars - Variables used by Tcl
_________________________________________________________________
DESCRIPTION
The following global variables are created and managed
automatically by the Tcl library. Except where noted below,
these variables should normally be treated as read-only by
application-specific code and by users.
env
This variable is maintained by Tcl as an array whose
elements are the environment variables for the process.
Reading an element will return the value of the
corresponding environment variable. Setting an element
of the array will modify the corresponding environment
variable or create a new one if it doesn't already
exist. Unsetting an element of env will remove the
corresponding environment variable. Changes to the env
array will affect the environment passed to children by
commands like exec. If the entire env array is unset
then Tcl will stop monitoring env accesses and will not
update environment variables.
errorCode
After an error has occurred, this variable will be set
to hold additional information about the error in a
form that is easy to process with programs. errorCode
consists of a Tcl list with one or more elements. The
first element of the list identifies a general class of
errors, and determines the format of the rest of the
list. The following formats for errorCode are used by
the Tcl core; individual applications may define addi-
tional formats.
ARITH code msg
This format is used when an arithmetic error |
occurs (e.g. an attempt to divide by zero in the |
expr command). Code identifies the precise error |
and msg provides a human-readable description of |
the error. Code will be either DIVZERO (for an |
attempt to divide by zero), DOMAIN (if an argument |
is outside the domain of a function, such as |
acos(-3)), IOVERFLOW (for integer overflow), |
OVERLFLOW (for a floating-point overflow), or UNK- |
NOWN (if the cause of the error cannot be deter- |
mined).
CHILDKILLED pid sigName msg
This format is used when a child process has been
killed because of a signal. The second element of
errorCode will be the process's identifier (in
decimal). The third element will be the symbolic
name of the signal that caused the process to ter-
minate; it will be one of the names from the
include file signal.h, such as SIGPIPE. The
fourth element will be a short human-readable mes-
sage describing the signal, such as ``write on
pipe with no readers'' for SIGPIPE.
CHILDSTATUS pid code
This format is used when a child process has
exited with a non-zero exit status. The second
element of errorCode will be the process's iden-
tifier (in decimal) and the third element will be
the exit code returned by the process (also in
decimal).
CHILDSUSP pid sigName msg
This format is used when a child process has been
suspended because of a signal. The second element
of errorCode will be the process's identifier, in
decimal. The third element will be the symbolic
name of the signal that caused the process to
suspend; this will be one of the names from the
include file signal.h, such as SIGTTIN. The
fourth element will be a short human-readable mes-
sage describing the signal, such as ``background
tty read'' for SIGTTIN.
NONE
This format is used for errors where no additional
information is available for an error besides the
message returned with the error. In these cases
errorCode will consist of a list containing a sin-
gle element whose contents are NONE.
POSIX errName msg
If the first element of errorCode is POSIX, then |
the error occurred during a POSIX kernel call.
The second element of the list will contain the
symbolic name of the error that occurred, such as
ENOENT; this will be one of the values defined in
the include file errno.h. The third element of
the list will be a human-readable message
corresponding to errName, such as ``no such file
or directory'' for the ENOENT case.
To set errorCode, applications should use library pro-
cedures such as Tcl_SetErrorCode and Tcl_PosixError, or |
they may invoke the error command. If one of these
methods hasn't been used, then the Tcl interpreter will
reset the variable to NONE after the next error.
errorInfo
After an error has occurred, this string will contain
one or more lines identifying the Tcl commands and pro-
cedures that were being executed when the most recent
error occurred. Its contents take the form of a stack
trace showing the various nested Tcl commands that had
been invoked at the time of the error.
tcl_precision
If this variable is set, it must contain a decimal |
number giving the number of significant digits to |
include when converting floating-point values to |
strings. If this variable is not set then 6 digits are |
included. 17 digits is ``perfect'' for IEEE floating- |
point in that it allows double-precision values to be |
converted to strings and back to binary with no loss of |
precision.
KEYWORDS
arithmetic, error, environment, POSIX, precision, subpro-
cess, variables
_________________________________________________________________
NAME
tell - Return current access position for an open file
SYNOPSIS
tell fileId
_________________________________________________________________
DESCRIPTION
Returns a decimal string giving the current access position
in fileId. FileId must have been the return value from a
previous call to open, or it may be stdin, stdout, or stderr
to refer to one of the standard I/O channels.
KEYWORDS
access position, file
_________________________________________________________________
NAME
time - Time the execution of a script
SYNOPSIS
time script ?count?
_________________________________________________________________
DESCRIPTION
This command will call the Tcl interpreter count times to
evaluate script (or once if count isn't specified). It will
then return a string of the form
503 microseconds per iteration
which indicates the average amount of time required per
iteration, in microseconds. Time is measured in elapsed
time, not CPU time.
KEYWORDS
script, time
_________________________________________________________________
NAME
trace - Monitor variable accesses
SYNOPSIS
trace option ?arg arg ...?
_________________________________________________________________
DESCRIPTION
This command causes Tcl commands to be executed whenever
certain operations are invoked. At present, only variable
tracing is implemented. The legal option's (which may be
abbreviated) are:
trace variable name ops command
Arrange for command to be executed whenever variable
name is accessed in one of the ways given by ops. Name
may refer to a normal variable, an element of an array,
or to an array as a whole (i.e. name may be just the
name of an array, with no parenthesized index). If
name refers to a whole array, then command is invoked
whenever any element of the array is manipulated.
Ops indicates which operations are of interest, and
consists of one or more of the following letters:
r Invoke command whenever the variable is read.
w Invoke command whenever the variable is writ-
ten.
u Invoke command whenever the variable is
unset. Variables can be unset explicitly
with the unset command, or implicitly when
procedures return (all of their local vari-
ables are unset). Variables are also unset
when interpreters are deleted, but traces
will not be invoked because there is no
interpreter in which to execute them.
When the trace triggers, three arguments are appended
to command so that the actual command is as follows:
command name1 name2 op
Name1 and name2 give the name(s) for the variable being
accessed: if the variable is a scalar then name1 gives
the variable's name and name2 is an empty string; if
the variable is an array element then name1 gives the
name of the array and name2 gives the index into the
array; if an entire array is being deleted and the
trace was registered on the overall array, rather than
a single element, then name1 gives the array name and
name2 is an empty string. Op indicates what operation
is being performed on the variable, and is one of r, w,
or u as defined above.
Command executes in the same context as the code that
invoked the traced operation: if the variable was
accessed as part of a Tcl procedure, then command will
have access to the same local variables as code in the
procedure. This context may be different than the con-
text in which the trace was created. If command
invokes a procedure (which it normally does) then the
procedure will have to use upvar or uplevel if it
wishes to access the traced variable. Note also that
name1 may not necessarily be the same as the name used
to set the trace on the variable; differences can
occur if the access is made through a variable defined
with the upvar command.
For read and write traces, command can modify the vari-
able to affect the result of the traced operation. If
command modifies the value of a variable during a read
or write trace, then the new value will be returned as
the result of the traced operation. The return value
from command is ignored except that if it returns an
error of any sort then the traced operation also
returns an error with the same error message returned |
by the trace command (this mechanism can be used to
implement read-only variables, for example). For write
traces, command is invoked after the variable's value
has been changed; it can write a new value into the
variable to override the original value specified in
the write operation. To implement read-only variables,
command will have to restore the old value of the vari-
able.
While command is executing during a read or write
trace, traces on the variable are temporarily disabled.
This means that reads and writes invoked by command
will occur directly, without invoking command (or any
other traces) again. However, if command unsets the |
variable then unset traces will be invoked.
When an unset trace is invoked, the variable has
already been deleted: it will appear to be undefined
with no traces. If an unset occurs because of a pro-
cedure return, then the trace will be invoked in the
variable context of the procedure being returned to:
the stack frame of the returning procedure will no
longer exist. Traces are not disabled during unset
traces, so if an unset trace command creates a new
trace and accesses the variable, the trace will be
invoked. Any errors in unset traces are ignored. |
If there are multiple traces on a variable they are
invoked in order of creation, most-recent first. If
one trace returns an error, then no further traces are
invoked for the variable. If an array element has a
trace set, and there is also a trace set on the array
as a whole, the trace on the overall array is invoked
before the one on the element.
Once created, the trace remains in effect either until
the trace is removed with the trace vdelete command
described below, until the variable is unset, or until
the interpreter is deleted. Unsetting an element of
array will remove any traces on that element, but will
not remove traces on the overall array.
This command returns an empty string.
trace vdelete name ops command
If there is a trace set on variable name with the
operations and command given by ops and command, then
the trace is removed, so that command will never again
be invoked. Returns an empty string.
trace vinfo name
Returns a list containing one element for each trace
currently set on variable name. Each element of the
list is itself a list containing two elements, which
are the ops and command associated with the trace. If
name doesn't exist or doesn't have any traces set, then
the result of the command will be an empty string.
KEYWORDS
read, variable, write, trace, unset
_________________________________________________________________
NAME
unknown - Handle attempts to use non-existent commands
SYNOPSIS
unknown cmdName ?arg arg ...?
_________________________________________________________________
DESCRIPTION
This command doesn't actually exist as part of Tcl, but Tcl
will invoke it if it does exist. If the Tcl interpreter
encounters a command name for which there is not a defined
command, then Tcl checks for the existence of a command
named unknown. If there is no such command, then the inter-
preter returns an error. If the unknown command exists,
then it is invoked with arguments consisting of the fully-
substituted name and arguments for the original non-existent
command. The unknown command typically does things like
searching through library directories for a command pro-
cedure with the name cmdName, or expanding abbreviated com-
mand names to full-length, or automatically executing unk-
nown commands as sub-processes. In some cases (such as
expanding abbreviations) unknown will change the original
command slightly and then (re-)execute it. The result of
the unknown command is used as the result for the original
non-existent command.
KEYWORDS
error, non-existent command
_________________________________________________________________
NAME
unset - Delete variables
SYNOPSIS
unset name ?name name ...?
_________________________________________________________________
DESCRIPTION
This command removes one or more variables. Each name is a
variable name, specified in any of the ways acceptable to
the set command. If a name refers to an element of an array
then that element is removed without affecting the rest of
the array. If a name consists of an array name with no
parenthesized index, then the entire array is deleted. The
unset command returns an empty string as result. An error
occurs if any of the variables doesn't exist, and any vari-
ables after the non-existent one are not deleted.
KEYWORDS
remove, variable
_________________________________________________________________
NAME
uplevel - Execute a script in a different stack frame
SYNOPSIS
uplevel ?level? arg ?arg ...?
_________________________________________________________________
DESCRIPTION
All of the arg arguments are concatenated as if they had
been passed to concat; the result is then evaluated in the
variable context indicated by level. Uplevel returns the
result of that evaluation.
If level is an integer then it gives a distance (up the pro-
cedure calling stack) to move before executing the command.
If level consists of # followed by a number then the number
gives an absolute level number. If level is omitted then it
defaults to 1. Level cannot be defaulted if the first com-
mand argument starts with a digit or #.
For example, suppose that procedure a was invoked from top-
level, and that it called b, and that b called c. Suppose
that c invokes the uplevel command. If level is 1 or #2 or
omitted, then the command will be executed in the variable
context of b. If level is 2 or #1 then the command will be
executed in the variable context of a. If level is 3 or #0
then the command will be executed at top-level (only global
variables will be visible).
The uplevel command causes the invoking procedure to disap-
pear from the procedure calling stack while the command is
being executed. In the above example, suppose c invokes the
command
uplevel 1 {set x 43; d}
where d is another Tcl procedure. The set command will
modify the variable x in b's context, and d will execute at
level 3, as if called from b. If it in turn executes the
command
uplevel {set x 42}
then the set command will modify the same variable x in b's
context: the procedure c does not appear to be on the call
stack when d is executing. The command ``info level'' may
be used to obtain the level of the current procedure.
Uplevel makes it possible to implement new control con-
structs as Tcl procedures (for example, uplevel could be
used to implement the while construct as a Tcl procedure).
KEYWORDS
context, stack frame, variables
_________________________________________________________________
NAME
upvar - Create link to variable in a different stack frame
SYNOPSIS
upvar ?level? otherVar myVar ?otherVar myVar ...?
_________________________________________________________________
DESCRIPTION
This command arranges for one or more local variables in the
current procedure to refer to variables in an enclosing pro-
cedure call or to global variables. Level may have any of
the forms permitted for the uplevel command, and may be
omitted if the first letter of the first otherVar isn't # or
a digit (it defaults to 1). For each otherVar argument,
upvar makes the variable by that name in the procedure frame
given by level (or at global level, if level is #0) accessi-
ble in the current procedure by the name given in the
corresponding myVar argument. The variable named by other-
Var need not exist at the time of the call; it will be
created the first time myVar is referenced, just like an
ordinary variable. Upvar may only be invoked from within
procedures. MyVar may not refer to an element of an array, |
but otherVar may refer to an array element. Upvar returns
an empty string.
The upvar command simplifies the implementation of call-by-
name procedure calling and also makes it easier to build new
control constructs as Tcl procedures. For example, consider
the following procedure:
proc add2 name {
upvar $name x
set x [expr $x+2]
}
Add2 is invoked with an argument giving the name of a vari-
able, and it adds two to the value of that variable.
Although add2 could have been implemented using uplevel
instead of upvar, upvar makes it simpler for add2 to access
the variable in the caller's procedure frame.
If an upvar variable is unset (e.g. x in add2 above), the |
unset operation affects the variable it is linked to, not |
the upvar variable. There is no way to unset an upvar vari- |
able except by exiting the procedure in which it is defined. |
However, it is possible to retarget an upvar variable by |
executing another upvar command.
KEYWORDS
context, frame, global, level, procedure, variable
_________________________________________________________________
NAME
while - Execute script repeatedly as long as a condition is
met
SYNOPSIS
while test body
_________________________________________________________________
DESCRIPTION
The while command evaluates test as an expression (in the
same way that expr evaluates its argument). The value of
the expression must a proper boolean value; if it is a true
value then body is executed by passing it to the Tcl inter-
preter. Once body has been executed then test is evaluated
again, and the process repeats until eventually test evalu-
ates to a false boolean value. Continue commands may be
executed inside body to terminate the current iteration of
the loop, and break commands may be executed inside body to
cause immediate termination of the while command. The while
command always returns an empty string.
KEYWORDS
boolean value, loop, test, while